e.printStackTrace equivalent in python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
Output:
This is the direct equivalent of Java's e.printStackTrace(). It prints the full traceback to stderr.
Capturing as a String
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
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
Logging Integration
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)
Output:
Python shows the full exception chain, similar to Java's getCause() chain.
Custom Exception Handler
Java vs Python Comparison
| Java | Python | Purpose |
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 + PrintWriter | traceback.format_exc() | Capture traceback as string |
e.getCause() | e.__cause__ | Get chained exception |
Thread.setDefaultUncaughtExceptionHandler | sys.excepthook | Global exception handler |
Common Pitfalls
- Calling
traceback.print_exc()outside an except block: It printsNoneType: Nonebecause there is no active exception. Only call it inside anexceptclause. - Using
print(e)instead oftraceback.print_exc():print(e)shows only the error message, not the file, line number, or call stack. Always usetracebackfor debugging. - Swallowing exceptions:
except: passhides 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 infinally.logger.exception()outside except: Liketraceback.print_exc(), it only works inside anexceptblock. Outside, it logsNoneType: Nonefor the exception info.
Summary
traceback.print_exc()is the direct equivalent of Java'se.printStackTrace()traceback.format_exc()captures the traceback as a string for logginglogger.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 eshows the full cause chain in tracebacks - Use
sys.excepthookfor global unhandled exception handling
Related reading
- Error after upgrading pip cannot import name 'main
- ERROR Cannot uninstall 'wrapt'. when installing tensorflow-gpu1.14
- ERROR Could not build wheels for scipy which use PEP 517 and cannot be installed directly
- ERROR Could not find a version that satisfies the requirement tensorflow from versions none ERROR No matching distribution found for tensorflow
- Erlang can not receive message from where it begins
- Erlang's let-it-crash philosophy - applicable elsewhere?
- ERROR Could not install packages due to an OSError WinError 5
- Error 'DataFrame' object has no attribute 'append
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.