Python Glossary Русский

all Python 3tracebackfunction

traceback.print_exception()

printing tracebacks

Prints the traceback of a given exception to stderr — like print_exc(), but for a saved exception object.

Syntax

traceback.print_exception(exc, /, limit=None, file=None, chain=True)

Since Python 3.10 it takes a single exception: print_exception(e); older code uses print_exception(*sys.exc_info()). By default (chain=True) the whole chain is printed: the cause from raise … from … ("The above exception was the direct cause") and the exception during whose handling the new one occurred. limit caps the number of frames, file= sets the stream.

Examples

# Python 3.10+
import io, traceback
try:
    try:
        int('x')
    except ValueError as e:
        raise RuntimeError('конфиг не прочитан') from e
except RuntimeError as err:
    saved = err
buf = io.StringIO()
traceback.print_exception(saved, file=buf)
print('direct cause' in buf.getvalue())  # → True
print(buf.getvalue().splitlines()[-1])  # → RuntimeError: конфиг не прочитан

See also

Open in the full glossarydocs.python.orgReport an inaccuracy