TracebackException Serializes Failure Details

Capture an exception with TracebackException, format its frames, and walk the explicit cause chain without printing to stderr.

PythonResilience

Code

pythonsnippet
29 lines
import traceback


def divide(a: int, b: int) -> float:
    return a / b


def main() -> None:
    try:
        divide(10, 0)
    except ZeroDivisionError as error:
        wrapped = traceback.TracebackException.from_exception(error)
        print('type:', wrapped.exc_type.__name__)
        print('frames:', len(wrapped.stack))
        text = ''.join(wrapped.format())
        print('formatted lines:', len(text.splitlines()))
        print(text.splitlines()[-1])

    try:
        raise ValueError('bad config') from KeyError('missing key')
    except ValueError as error:
        chained = traceback.TracebackException.from_exception(error)
        print('cause type:', chained.__cause__.exc_type.__name__)
        print('cause message:', chained.__cause__)
        print('suppressed context:', chained.__suppress_context__)


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

type: ZeroDivisionError
frames: 2
formatted lines: 7
ZeroDivisionError: division by zero
cause type: KeyError
cause message: 'missing key'
suppressed context: True

What the code does

One way to read it: the functions divide and main, doing all the work.

The ValueError raise sits inside a try: execution reaches it unconditionally, and the surrounding handler catches it.

Caveats

  • Requires traceback as a package; the snippet will not run without it.

Using it

The primary signature is def divide(a: int, b: int) -> float

Look for the type:, frames:, formatted lines: prefixes when the file runs; they tie each line to its step.

Running the file executes main, which drives divide in order.

Key statements

def divide(a: int, b: int) -> float:
    return a / b
except ZeroDivisionError as error:
    wrapped = traceback.TracebackException.from_exception(error)
    print('type:', wrapped.exc_type.__name__)
    print('frames:', len(wrapped.stack))
    text = ''.join(wrapped.format())
    print('formatted lines:', len(text.splitlines()))
    print(text.splitlines()[-1])
except ValueError as error:
    chained = traceback.TracebackException.from_exception(error)
    print('cause type:', chained.__cause__.exc_type.__name__)
    print('cause message:', chained.__cause__)
    print('suppressed context:', chained.__suppress_context__)

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `ValueError` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
What does TracebackException Serializes Failure Details print when run?
Run it as a complete program — the output lines carry labels such as `type:`, `frames:`, `formatted lines:`.