关于python中的异常
1. try....except(except1,except2),可以捕获多个异常,如果都未捕获到,则程序终止
try:
a=[1,2,3]
print(a[4])
except(IndexError, ZeroDivisionError):
print('发生了错误')
print('1111')
2.普通异常的捕获:
a=input('请输入整数:')
try:
a= int(a)
print(a**2)
except Exception as e:
print(e)
print(1111)
测试输入非整数:
3.处理异常时,打印堆栈信息,需要引入traceback包
import traceback
# 打印堆栈
a = input("请输入整数")
try:
a = int(a)
print(a ** 2)
except Exception as e:
# 引入traceback,程序不会退出
traceback.print_exc()
print('1111111')
4.try...except...finally:
<1>.try里面发生了异常,except捕获到了,finally会执行
import traceback
a = input("请输入整数")
try:
a = int(a)
print(a ** 2)
except Exception as e:
# 引入traceback,程序不会退出
traceback.print_exc()
finally:
print('finally')
<2>.try里面没有发生异常,finally也会执行:
还是上面的代码,测试未发生异常的示例:
<3>.try里面发生了异常,except没有捕获到,finnally也会执行
import traceback
# 打印堆栈
a = input("请输入整数")
try:
a = int(a)
print(a ** 2)
except ZeroDivisionError as e:
# 引入traceback,程序不会退出
traceback.print_exc()
finally:
print('finally')
` 上面的示例,except捕获的异常不对,此时finally也会执行
如果将finally去掉,改成print(),则print不会执行:
import traceback
a = input("请输入整数")
try:
a = int(a)
print(a ** 2)
except ZeroDivisionError as e:
# 引入traceback,程序不会退出
traceback.print_exc()
print('finally')