+-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
3、异常处理
1.try语句
try:
检测范围
except Exception [as reason]:
出现Exception后处理的代码
可以有多个except与try组合,因为检测范围中肯能会产生多个异常,可以用多个except与try组合来关注感兴趣的异常
可以同一处理多类异常 except后要用()把多个需要同一处理的异常括起来
try:
int('abc')
sum = 1+'1'
f = open('我是一个不存在的文档.txt')
print(f.read())
f.close()
except (OSError, ValueError,TypeError)as reason:
print('出错啦T_T\n错误原因是:' + str(reason))
2.try finally语句
try:
检测范围
except Exception [as reason]:
出现Exception后处理的代码
finally:
一定要做的事情(比如出错后可以在这里把文件关闭)
try:
f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T
print(f.read())
except OSError as reason:
print('出错啦:' + str(reason))
finally:
if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功
f.close()
3、raise语句(引发一个异常)
raise 异常名字
try:
for i in range(3):
for j in range(3):
if i == 2:
raise KeyboardInterrupt
print(i, j)
except KeyboardInterrupt:
print('退出啦!')