try-except语句
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
实例1:
1 try:
2 f = open('TE.txt')
3 print(f.read())
4 f.close()
5 except OSError:
6 print('文件打开过程中出错了!!!')
实例2:
1 try:
2 f = open('TE.txt')
3 print(f.read())
4 f.close()
5 except OSError as reason:
6 print('文件打开出错原因是:\n' + str(reason))
实例3:
1 try:
2 sum = 1 + '1'
3 f = open('TE.txt')
4 print(f.read())
5 f.close()
6 except OSError as reason:
7 print('文件打开出错原因是:\n' + str(reason))
8 except TypeError as reason:
9 print('类型出错原因是:\n' + str(reason))
实例4(多个异常统一处理):
1 try:
2 sum = 1 + '1'
3 f = open('TE.txt')
4 print(f.read())
5 f.close()
6 except(OSError, TypeError):
7 print('出错了')
注:try语句一旦检测到异常,剩下的语句将不会被执行
try-finally语句
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会被执行的代码
实例5:
1 try:
2 f = open('test.txt')
3 print(f.read())
4 sum = 1 + '1'
5 except (OSError,TypeError)as reason:
6 print('出错了\n原因是:' + str(reason))
7 finally:
8 f.close()
raise语句可以自己抛出一个异常