异常处理学习

异常处理学习学习笔记

异常处理学习

try:
检测范围
except Exception[as reason]:
出现Exception后处理的代码
finally:
无论如何都会被执行的代码

e.g.

1
2
3
4
5
6
7
8
9
try:
f = open('test.txt','w')
f.write(sum)
sum = 1 + 1
print(sum)
except (SyntaxError,TypeError,IndentationError) as reason:
print('Your error is :n' + str(reason) +'n error type is:n' + str(type(reason)))
finally:
f.close()

1
2
3
4
5
6
7
8
9
try:
f = open('test.txt','w')
f.write(sum)
sum = 1 + 1
print(sum)
except Exception as reason:
print('Your error is :n' + str(reason) +'n error type is:n' + str(type(reason)))
finally:
f.close()

主动抛出异常:

1
2
3
4
>>> raise TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError