traceback.format_exc Captures The Report

traceback.format_exc captures the full interpreter traceback inside except blocks, format_exception_only keeps just the error line, idle calls stay safe.

PythonResilience

Code

pythonsnippet
22 lines
import traceback


def divide(a, b):
    return a / b


try:
    divide(10, 0)
except ZeroDivisionError:
    # format_exc 拿到与解释器打印一致的完整回溯文本
    report = traceback.format_exc()
    print('has error  :', 'ZeroDivisionError' in report)
    print('has frame  :', 'divide' in report)
    print('lines      :', len(report.splitlines()))

# format_exception_only 只要异常行,不要整段回溯
only = traceback.format_exception_only(ZeroDivisionError, ZeroDivisionError('division by zero'))
print('only       :', only[0].strip())

# 无活动异常时 format_exc 返回 NoneType 字样,不会抛错
print('idle       :', 'NoneType' in traceback.format_exc())

Output

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

has error  : True
has frame  : True
lines      : 7
only       : ZeroDivisionError: division by zero
idle       : True

How the snippet works

Count the function divide as the entire surface area of traceback.format_exc Captures The Report.

What to watch for

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

Applying it

The main signature appears as def divide(a, b)

The run leaves labeled output — has error :, has frame :, lines : — when the file runs.

Import divide from the file and call it — the rest of the code is implementation detail.

Statements that matter

except ZeroDivisionError:
    # format_exc 拿到与解释器打印一致的完整回溯文本
    report = traceback.format_exc()
    print('has error  :', 'ZeroDivisionError' in report)
    print('has frame  :', 'divide' in report)
    print('lines      :', len(report.splitlines()))
def divide(a, b):
    return a / b

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `traceback`. The file defines `divide` at load time.