![图片[1]-python怎么打印异常原因-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5dc1069e0fd0c542.gif)
捕获异常的操作
为了能够捕获异常,"except"语句必须有用相同的异常来抛出类对象或者字符串。
使用except而不带任何异常类型
你可以不带任何异常类型使用except,如下实例以上方式try-except语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。
print("test2")
try:
x=1
y=0
z=x/y
except:#捕获所有异常
print('thereisproblem')
else:
print('noproblem')
finally:
print('endtest2')
使用except而带多种异常类型
你也可以使用相同的except语句来处理多个异常信息,这些异常将被放在一个括号里成为一个元组,如下所示:
try: 正常的操作except(Exception1[,Exception2[,...ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码else: 如果没有异常执行这块代码
print('test3')
try:
x=1
y=0
z=x/y
except(NameError,ZeroDivisionError):
print("problemis(NameError,ZeroDivisionError)")
except(RuntimeError,TypeError):
print("problemis(RuntimeError,TypeError)")
except:
print("problem")
raise
else:
print("noproblem")
finally:
print('endtest3')
最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。
importsys
try:
f=open('myfile.txt')
s=f.readline()
i=int(s.strip())
#exceptOSErroraserr:
#print("OSerror:{0}".format(err))
exceptValueError:
print("Couldnotconvertdatatoaninteger.")
except:
print("Unexpectederror:",sys.exc_info()[0])
foriinsys.exc_info():
print(i)
raiseException('linexxx')
finally:
print("end")原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容