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
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01