之前大多情况了下直接打印:
print(f"Caught an exception: {e}")
try: # 尝试执行的代码块 risky_operation() except SomeSpecificException as e: # 处理特定异常 print(f"Caught an exception: {e}") except AnotherSpecificException: # 处理另一种特定异常 print("Caught another specific exception") except Exception as e: # 处理所有其他异常 print(f"An error occurred: {e}") else: # 如果没有异常,执行这个代码块 print("No exceptions occurred!") finally: # 无论是否发生异常,这个代码块都会执行 print("Execution completed.")
1. 使用 traceback
模块
traceback
模块提供了一些用于格式化和输出异常信息的工具。你可以使用 traceback.print_exc()
或 traceback.format_exc()
来获取详细的异常堆栈信息。
import traceback try: # 故意制造一个异常 result = 10 / 0 except Exception: print("发生异常:") traceback.print_exc()
格式化输出
你可以自定义输出格式,通过 str()
或 repr()
函数来控制输出的字符串形式。
import traceback def pretty_print_exception(e): error_message = f"发生异常: {str(e)}\n" error_message += "详细信息:\n" error_message += traceback.format_exc() return error_message try: # 故意制造一个异常 result = 10 / 0 except Exception as e: print(pretty_print_exception(e))
使用 f-string
(Python 3.6 及以上)
通过 f-string
可以使打印信息更加简洁和可读:
try: result = 10 / 0 except ZeroDivisionError as e: print(f"发生异常: {e} (类型: {type(e).__name__})")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2019-07-24 常用书签