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 块中重新引发异常?


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01