How to re-raise an exception in nested try/except blocks?(如何在嵌套的 try/except 块中重新引发异常?)
问题描述
我知道如果我想重新引发异常,我只需在相应的 except 块中使用不带参数的 raise.但是给定一个嵌套的表达式,如
I know that if I want to re-raise an exception, I simple use raise without arguments in the respective except block. But given a nested expression like
try:
something()
except SomeError as e:
try:
plan_B()
except AlsoFailsError:
raise e # I'd like to raise the SomeError as if plan_B()
# didn't raise the AlsoFailsError
如何在不破坏堆栈跟踪的情况下重新引发 SomeError?在这种情况下,单独的 raise 会重新引发最近的 AlsoFailsError.或者我如何重构我的代码以避免这个问题?
how can I re-raise the SomeError without breaking the stack trace? raise alone would in this case re-raise the more recent AlsoFailsError. Or how could I refactor my code to avoid this issue?
推荐答案
从 Python 3 开始,回溯存储在异常中,因此一个简单的 raise e 将做(大部分)正确的事情:
As of Python 3 the traceback is stored in the exception, so a simple raise e will do the (mostly) right thing:
try:
something()
except SomeError as e:
try:
plan_B()
except AlsoFailsError:
raise e # or raise e from None - see below
产生的回溯将包括一个额外的通知,即 SomeError 在处理 AlsoFailsError 时发生(因为 raise e 在 except AlsoFailsError).这是一种误导,因为实际发生的事情是相反的 - 我们遇到了 AlsoFailsError,并在尝试从 SomeError 中恢复时对其进行了处理.要获得不包含 AlsoFailsError 的回溯,请将 raise e 替换为 raise e from None.
The traceback produced will include an additional notice that SomeError occurred while handling AlsoFailsError (because of raise e being inside except AlsoFailsError). This is misleading because what actually happened is the other way around - we encountered AlsoFailsError, and handled it, while trying to recover from SomeError. To obtain a traceback that doesn't include AlsoFailsError, replace raise e with raise e from None.
在 Python 2 中,您将异常类型、值和回溯存储在局部变量中,并使用 raise 的三参数形式:
In Python 2 you'd store the exception type, value, and traceback in local variables and use the three-argument form of raise:
try:
something()
except SomeError:
t, v, tb = sys.exc_info()
try:
plan_B()
except AlsoFailsError:
raise t, v, tb
这篇关于如何在嵌套的 try/except 块中重新引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在嵌套的 try/except 块中重新引发异常?
基础教程推荐
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
