def sqrt(x):
if not isinstance(x,(int,float)): #检查x是否是整型/浮点型
raise TypeError('x must be numeric')
elif x < 0: #检查x是否是非负数
raise ValueError('x cannot be negative')
1
2
3
4
5
3.执行错误检测和简单实现的平衡
try:
fp = open('sample.txt')
except IOError as e: #e表示抛出的异常的实例
print ('Unable to open the file:',e)
1
2
3
4
3.try-except结构的应用
捕获多个异常:
age = -1
while age < =0:
try:
age = int(input('Enter your age in years:'))
if age <= 0:
print('Your age must be positive')
except (ValueError,EOFError): #用一个tuple元祖捕捉函数(int())参数类型不正确和控制台输入
出错异常
print(‘Invalid response’)
1
2
3
4
5
6
7
8
9
若希望在不输出‘‘Invalid response’’的情况下继续while循环,可改为:
age = -1
while age < =0:
try:
age = int(input('Enter your age in years:'))
if age <= 0:
print('Your age must be positive')
except ValueError:
print(‘That is an invalid age specification')
except EOFError:
print(‘There was an unexpected error reading input’)
1
2
3
4
5
6
7
8
9
10
希望异常能中断循环并传达给上下文:
可以将上例改为
age = -1
while age < =0:
try:
age = int(input('Enter your age in years:'))
if age <= 0:
print('Your age must be positive')
except ValueError:
print(‘That is an invalid age specification')
except EOFError:
print(‘There was an unexpected error reading input’)
raise #重新抛出目前正在处理的相同的异常
---------------------
【转载,仅作分享,侵删】
作者:琪仔要转行回coder
来源:CSDN
原文:https://blog.csdn.net/lllllaaa77/article/details/87539597
版权声明:本文为博主原创文章,转载请附上博文链接!