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
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
