Python如何在抛出异常后打印字典的具体内容?
实现方法
可以实现,有两种常用方案可选:
方案1:自定义异常类(更灵活)
直接继承你需要抛出的原生异常类,在实例化时传入目标字典,重写__str__方法拼接输出格式即可,示例代码如下:
d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]} # 自定义带字典输出的TypeError子类 class TypeErrorWithDict(TypeError): def __init__(self, msg, target_dict): super().__init__(msg) self.target_dict = target_dict def __str__(self): # 按要求格式化字典内容 dict_content = "" for key, val_list in self.target_dict.items(): dict_content += f"\n\n{key}" for num in val_list: dict_content += f"\n{num}" return f"{super().__str__()}{dict_content}" # 抛出异常时传入字典 raise TypeErrorWithDict("This is a TypeError.", d)
运行后输出的异常信息完全匹配你给出的示例格式,默认回溯栈打印完成后会自动带出格式化的字典内容。
方案2:修改全局异常钩子(无需改原有抛异常逻辑)
如果你不想修改原有抛出异常的代码,可以通过重写sys.excepthook实现全局拦截特定类型的异常,额外打印字典内容:
import sys d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]} def custom_exception_handler(exc_type, exc_val, exc_tb): # 先打印原生的异常回溯信息 sys.__excepthook__(exc_type, exc_val, exc_tb) # 拦截TypeError后打印字典 if exc_type is TypeError: print() for key, val_list in d.items(): print(key) for num in val_list: print(num) print() sys.excepthook = custom_exception_handler # 原有抛异常的代码不需要改动 raise TypeError("This is a TypeError.")
两种方案都可以达到你要的效果,按需选择即可。
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

