← 中文资源

简体中文版本

TracebackException 序列化异常详情

用 TracebackException 捕获异常,格式化栈帧,并在不写 stderr 的情况下遍历显式 cause 链。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

逻辑集中在函数 divide、main里。 ValueError 在 try 块内抛出——谁来接住由匹配的 except 子句决定,与任何输入检查无关。

使用要点

  • 跑完文件,输出里会留下标记——type:、frames:、formatted lines:。
  • 运行整个文件:main 会依次驱动 divide。

常见问题

这个示例会校验输入吗?

不会——ValueError 在 try 块内抛出:执行到这一行就必然抛出,由外围的 except 子句决定谁来接住。示例里没有输入校验。

运行「TracebackException 序列化异常详情」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 type:、frames:、formatted lines: 标签标明各步骤。

入口签名:def divide(a: int, b: int) -> float

核心语句

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__)

代码示例

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()