一、常见的异常类型:
1.ZeroDivision:除零/取模所有的数据类型。
2.IndexError:序列中没有此索引。
3.KeyError:映射中没有这个键。
4.NameError:未生明/初始化对象(没有属性值)。
5.SyntaxError:python语法错误。
6.ValueError:传入无效的参数。
二、异常处理的机制:
1.
try:
pass #可能会出先异常的代码
except KeyError: #异常类型例如KeyError
pass #异常处理的代码
2.多个except结构
异常类型是从小到大,BaseException是最大的异常类型。
try:
pass
except Exception1:
pass
except Exception2:
pass
except BaseException:
pass
3.try...except...else结构:如果try块中没有抛出异常,则执行else块,如果try中抛出异常,则执行else块。
try:
pass
except BaseException as e:
print('出错了',e)
else:
pass
4.try...except...else...finally结构
finally块无论是否发生异常都会被执行,能常用来释放块中申请的资源。
try:
pass
except BaseException as e:
print('出错了',e)
else:
pass
finally:
print('程序结束')
三、异常处理的模块
traceback模块打印异常信息。
import_traveback
try:
pass
ecept:
traceback.print_exc()