1.使用方法
try:
print("尝试执行代码")
except Exception as e:
print(f"发生了错误: {e}")
else:
print("没有发生错误")
finally:
print("无论是否发生错误,都会执行这段代码")
2.捕获多种类型的异常
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("无效的数值")
except Exception as e:
print(f"发生了其他错误: {e}")
3.捕获异常后打印
(1)打印异常消息
try:
# 可能引发异常的代码
1 / 0
except Exception as e:
print(f"发生异常: {e}")
(2)打印异常类型
try:
1 / 0
except Exception as e:
print(f"异常类型: {type(e).__name__}")
(3)打印标准错误(跟踪回溯)
import traceback
try:
1 / 0
except Exception as e:
print("异常发生了:")
traceback.print_exc()
(4)打印文件名和行号
try:
1 / 0
except Exception as e:
import sys
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = exc_tb.tb_frame.f_code.co_filename
line_no = exc_tb.tb_lineno
print(f"异常发生在文件 {fname} 的第 {line_no} 行")