如何打印异常链的所有异常__str__表示且无冗余回溯信息
简洁打印Python异常链的方法
当使用print(ex)打印异常时,只会输出异常链的最后一个异常,无法看到引发它的根源异常。而traceback.print_exc()会输出包含行号的完整回溯信息,对于简单输入错误来说过于冗余。我们可以通过遍历异常链的方式,实现简洁的异常历史列表打印。
解决方案
利用Python异常对象的__cause__属性(当使用raise ... from ex显式关联异常链时),循环遍历并打印每个异常的类型与核心消息。如果是隐式生成的异常链(未使用from语句),则可以使用__context__属性。
修改后的示例代码
def test_with_context(context: str, test: int): try: assert isinstance(test, int) assert test > 4, "Test must be greater than 4" assert test < 6, "Test must be smaller than 6" except AssertionError as ex: raise ValueError(f"Invalid test for context {context}") from ex try: test_with_context("ExampleContext", 8) except ValueError as ex: print("Value Test Failed:") # 遍历异常链 current_ex = ex while current_ex: print(f"{type(current_ex).__name__}: {current_ex}") # 切换到上一级异常 current_ex = current_ex.__cause__
输出结果
Value Test Failed: ValueError: Invalid test for context ExampleContext AssertionError: Test must be smaller than 6
补充说明
- 若异常链是隐式生成的(未使用
raise ... from),需将current_ex.__cause__替换为current_ex.__context__,同时可结合__suppress_context__属性判断是否需要打印上下文异常。 - 该方式仅保留异常类型与核心提示,完全不输出回溯行号,满足简洁输出的需求。
内容的提问来源于stack exchange,提问作者Fyrefly
相关产品推荐
相关产品推荐

