@zzy0471
2018-04-09T23:11:15.000000Z
字数 741
阅读 1095
Python
Python通过try except else finally
捕获异常,如:
try:
num = 10 / 0
except ZeroDivisionError as e:
print('error:', e)
else:
print('no error')
finally:
print('finished')
其中,try
和except
是必需的,else
和finally
是可选的,except
可以有多个,待捕获的异常逐渐泛化。常用内置异常可在官网查看
关键字raise
用了抛出异常:
def set_age(age):
if not isinstance(age, int):
raise ValueError('only need int')
print('age is ', age)
try:
set_age('100')
except ValueError as e:
print('error:', e)
except Exception as e:
print('error', e)
class InvalidRange(ValueError):
pass
def set_age(age):
if not isinstance(age, int):
raise ValueError('only need int')
if age <= 0 or age >120:
raise InvalidRange('out of range(0,120)')
print('age is ', age)
try:
set_age(-1)
except InvalidRange as e:
print('error:', e)
except ValueError as e:
print('error:', e)
except Exception as e:
print('error', e)