--raise
>>> raise IOError('This is a test!')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
raise IOError('This is a test!')
OSError: This is a test!
 
--try except
def get_age():
while True:
try:
n = int(input('How old are you? '))
return n
except ValueError:
print('Please enter an integer value.')
 
运行结果:
>>> get_age()
How old are you? 30
30
>>> get_age()
How old are you? aaa
Please enter an integer value.
How old are you? 28
28
 
--捕获多种异常
try:
语句
except(ValueError, TypeError):
语句
 
try:
语句
except ValueError:
语句
except TypeError:
语句
 
--捕获所有异常
try:
语句
except:
语句
 
--清理操作
try:
语句
except:
语句
finally:
语句
 
posted on 2017-02-06 20:14  john2017  阅读(117)  评论(0编辑  收藏  举报