python-3.x - 在 Python 中捕获外部异常
问题描述
我的代码试图做某事,但它触发了一个错误...触发另一个错误。因此,错误消息如下所示:
SillyError: you can`t do that becuz blablabla
The above exception was the direct cause of the following exception:
LoopyError: you can`t do that becuz blobloblo
我想创建一个try
except
仅捕获此特定错误二重奏的块。但是,我只能抓住第一个,因为一旦我抓住了,第二个就没有机会触发了。
另一个问题是关于捕获任何一个异常,但我只想在两个异常都被连续触发时才捕获。有办法吗?
解决方案
如果您有 try\except,您将始终根据外部异常捕获错误。但是,您确实可以选择传递您不想处理的任何异常。
在此代码中,ZeroDivisionError 被捕获并包装在另一个异常中,然后由调用代码捕获。调用代码检查内部异常并决定是否在堆栈中重新引发异常。
def xtest():
try:
a = 1/0 # exception - division by zero
except ZeroDivisionError as e:
raise Exception("Outer Exception") from e # wrap exception (e not needed for wrap)
try:
xtest()
except Exception as ex:
print(ex) # Outer Exception
print(ex.__cause__) # division by zero
if (str(ex) == "Outer Exception" and str(ex.__cause__) == "division by zero"):
print("Got both exceptions")
else:
raise # pass exception up the stack
只是为了完成,您还可以根据异常类名称进行检查:
if (type(ex).__name__ == "Exception" and type(ex.__cause__).__name__ == "ZeroDivisionError"):
print("Got both exceptions")
@ShadowRanger 指出只检查类类型而不是类名可能会更快:
if (type(ex) == Exception and type(ex.__cause__) == ZeroDivisionError):
print("Got both exceptions")
推荐阅读
- javascript - 崇高的文本 - jsprettier:无法理解这个错误为什么它显示
- android - Android MMS 应用程序是否使用通用 API/存储来保存/检索 MMS?
- serverless-framework - 无服务器 - 对多个功能使用相同的端点
- ios - React Native DateTimepicker 适用于 Android 但不适用于 IOS
- jmeter - jmeter cli工具可以记录测试脚本吗?
- javascript - 单击发送按钮错误 500 时添加更多接收电子邮件
- python - 如何调用嵌套循环中的值?
- php - 如何将我的 Laravel 项目 [views] 文件连接到使用 Jetstream 创建的 Route Auto?
- reactjs - 为什么在 MUI 中忽略自定义调色板?
- python - 关于深度学习中的tqdm