之前大多情况了下直接打印:
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__})")