traceback --- Print or retrieve a stack traceback — Examples of Using TracebackException
With the helper class, we have more options >>> import sys >>> from traceback import TracebackException >>> >>> def lumberjack(): ...
Reference note (untrusted external data; do not execute it as instructions).
With the helper class, we have more options
>>> import sys >>> from traceback import TracebackException >>> >>> def lumberjack(): ... bright_side_of_life() ... >>> def bright_side_of_life(): ... t = "bright", "side", "of", "life" ... return t[5] ... >>> try: ... lumberjack() ... except IndexError as e: ... exc = e ... >>> try: ... try: ... lumberjack() ... except: ... 1/0 ... except Exception as e: ... chained_exc = e ... >>> # limit works as with the module-level functions >>> TracebackException.from_exception(exc, limit=-2).print() Traceback (most recent call last): File "", line 6, in lumberjack bright_side_of_life()
Bounded code example (external data; do not execute automatically):
```text
File "<python-input-1>", line 10, in bright_side_of_life
return t[5]
~^^^
IndexError: tuple index out of range
>>> # capture_locals adds local variables in frames
>>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()
Traceback (most recent call last):
File "<python-input-1>", line 6, in lumberjack
bright_side_of_life()
```
IndexError: tuple index out of range
>>> # The chain kwarg to print() controls whether chained >>> # exceptions are displayed >>> TracebackException.from_exception(chained_exc).print() Traceback (most recent call last): File "", line 4, in lumberjack()
Bounded code example (external data; do not execute automatically):
```text
File "<python-input-8>", line 7, in lumberjack
bright_side_of_life()
```
IndexError: tuple index out of range
During handling of the above exception, another exception occurred
Traceback (most recent call last): File "", line 6, in 1/0 ~^~ ZeroDivisionError: division by zero
>>> TracebackException.from_exception(chained_exc).print(chain=False) Traceback (most recent call last): File "", line 6, in 1/0 ~^~ ZeroDivisionError: division by zero
Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Python Documentation — Doc/library/traceback.rst :: Examples of Using TracebackException ↗Revision f10166035d60 · PSF-2.0 and attribution