error handling
exception handling
python tracing
debug python
python exceptions

e.printStackTrace equivalent in python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Java's e.printStackTrace() prints the full exception stack trace to stderr. Python's equivalent is traceback.print_exc() from the traceback module, which prints the current exception's traceback in the same format Python uses for unhandled exceptions. You can also use traceback.format_exc() to capture the stack trace as a string for logging.

Basic Equivalent

python
1import traceback
2
3try:
4    result = 1 / 0
5except Exception:
6    traceback.print_exc()

Output:

 
1Traceback (most recent call last):
2  File "example.py", line 4, in <module>
3    result = 1 / 0
4ZeroDivisionError: division by zero

This is the direct equivalent of Java's e.printStackTrace(). It prints the full traceback to stderr.

Capturing as a String

python
1import traceback
2
3try:
4    data = {"key": "value"}
5    print(data["missing"])
6except KeyError:
7    error_str = traceback.format_exc()
8    print(f"Caught error:\n{error_str}")
9
10    # Or log it
11    import logging
12    logging.error("Failed to access key:\n%s", traceback.format_exc())

format_exc() returns the traceback as a string instead of printing it. This is useful for sending to log files, error tracking services, or custom error handlers.

Using the Exception Object

python
1import traceback
2
3try:
4    int("not_a_number")
5except ValueError as e:
6    # Print just the exception message (like Java's e.getMessage())
7    print(f"Error: {e}")
8    # Output: Error: invalid literal for int() with base 10: 'not_a_number'
9
10    # Print the full traceback (like Java's e.printStackTrace())
11    traceback.print_exc()
12
13    # Get traceback from the exception object directly (Python 3.10+)
14    tb_lines = traceback.format_exception(e)
15    print("".join(tb_lines))

In Python 3.10+, traceback.format_exception(e) accepts just the exception object. In earlier versions, pass all three arguments: traceback.format_exception(type(e), e, e.__traceback__).

The traceback Module Functions

python
1import traceback
2import sys
3
4try:
5    open("/nonexistent/file.txt")
6except FileNotFoundError:
7    # Print to stderr (default), equivalent to e.printStackTrace()
8    traceback.print_exc()
9
10    # Print to a specific file
11    traceback.print_exc(file=sys.stdout)
12
13    # Get as string
14    tb_str = traceback.format_exc()
15
16    # Get exception info tuple (type, value, traceback)
17    exc_type, exc_value, exc_tb = sys.exc_info()
18
19    # Print with limit on traceback depth
20    traceback.print_exc(limit=2)
21
22    # Extract structured traceback data
23    tb_list = traceback.extract_tb(exc_tb)
24    for frame in tb_list:
25        print(f"  File {frame.filename}, line {frame.lineno}, in {frame.name}")

Logging Integration

python
1import logging
2
3logging.basicConfig(level=logging.DEBUG)
4logger = logging.getLogger(__name__)
5
6try:
7    result = some_function()
8except Exception:
9    # logger.exception() automatically includes the traceback
10    logger.exception("Failed to call some_function")
11
12    # Equivalent manual approach
13    logger.error("Failed to call some_function", exc_info=True)
14
15    # Or with traceback.format_exc()
16    import traceback
17    logger.error("Failed:\n%s", traceback.format_exc())

logger.exception() is the most Pythonic way to log exceptions with stack traces. It logs at ERROR level and automatically appends the current exception's traceback.

Nested Exceptions (Exception Chaining)

python
1import traceback
2
3try:
4    try:
5        int("abc")
6    except ValueError as e:
7        raise RuntimeError("Processing failed") from e
8except RuntimeError:
9    traceback.print_exc()

Output:

 
1Traceback (most recent call last):
2  File "example.py", line 4, in <module>
3    int("abc")
4ValueError: invalid literal for int() with base 10: 'abc'
5
6The above exception was the direct cause of the following exception:
7
8Traceback (most recent call last):
9  File "example.py", line 6, in <module>
10    raise RuntimeError("Processing failed") from e
11RuntimeError: Processing failed

Python shows the full exception chain, similar to Java's getCause() chain.

Custom Exception Handler

python
1import traceback
2import sys
3
4def global_exception_handler(exc_type, exc_value, exc_tb):
5    """Custom handler for uncaught exceptions."""
6    error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
7    # Log to file, send to error service, etc.
8    with open("crash.log", "a") as f:
9        f.write(error_msg)
10    print(f"Fatal error: {exc_value}", file=sys.stderr)
11
12# Install the handler
13sys.excepthook = global_exception_handler

Java vs Python Comparison

JavaPythonPurpose
e.printStackTrace()traceback.print_exc()Print traceback to stderr
e.getMessage()str(e)Get error message
e.getStackTrace()traceback.extract_tb(e.__traceback__)Get structured stack frames
StringWriter + PrintWritertraceback.format_exc()Capture traceback as string
e.getCause()e.__cause__Get chained exception
Thread.setDefaultUncaughtExceptionHandlersys.excepthookGlobal exception handler

Common Pitfalls

  • Calling traceback.print_exc() outside an except block: It prints NoneType: None because there is no active exception. Only call it inside an except clause.
  • Using print(e) instead of traceback.print_exc(): print(e) shows only the error message, not the file, line number, or call stack. Always use traceback for debugging.
  • Swallowing exceptions: except: pass hides errors completely. At minimum, log the traceback before suppressing the exception.
  • sys.exc_info() in finally blocks: In Python 3, sys.exc_info() is cleared after the except block exits. Save it in a variable if you need it in finally.
  • logger.exception() outside except: Like traceback.print_exc(), it only works inside an except block. Outside, it logs NoneType: None for the exception info.

Summary

  • traceback.print_exc() is the direct equivalent of Java's e.printStackTrace()
  • traceback.format_exc() captures the traceback as a string for logging
  • logger.exception("message") is the most Pythonic way to log exceptions with tracebacks
  • Python 3.10+ simplifies traceback.format_exception(e) to accept just the exception object
  • Exception chaining with raise ... from e shows the full cause chain in tracebacks
  • Use sys.excepthook for global unhandled exception handling

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.