python - 如果与 catch 子句相对应的 finally 子句包含 return 语句,如何捕获在 catch 子句中引发的异常?
问题描述
假设:
TEF
是一个try-except-finally
块。- 从
try
条款中提出了一个例外TEF
F
块的 finally 子句T
包含一个返回语句TEF
包含一个 except 子句E
e
内部引发异常E
- 我们如何
e
从子句F
之外和子句之外捕获E
?
如果这令人困惑,那么一些代码如下所示:
def e():
out = "hello world"
try:
raise ValueError("my name is Sarah")
except BaseException as exc:
# HOW DO I CATCH THE FIRST OF THE FOLLOWING
# exceptions from outside of this, current,
# except clause?
raise ValueError("secret info it would be good to know")
raise AttributeError
raise type("Hell", (Exception,), dict())()
[0, 1, 2][99999]
class AnythingYouCanThinkOf(Exception):
pass
raise AnythingYouCanThinkOf
out = "definitely not `hello world`"
finally:
return out
print(e())
print("No error!!! wowza!")
上面的代码打印:
hello world
No error!!! wowza!
如果我们注释掉该行,out = "hello world"
那么我们得到UnboundLocalError: local variable 'out' referenced before assignment
. 但是,我仍然不确定如何恢复ValueError("secret info it would be good to know")
此外,如果您将几乎相同的代码放在函数之外e
,您会得到非常不同的结果。为什么?
if True:
out = "hello world"
try:
raise ValueError("my name is Bob")
except BaseException as exc:
# HOW DO I CATCH THE FIRST OF THE FOLLOWING
# exceptions from outside of this, current,
# except clause?
raise ValueError("what is this madness?")
class AnythingYouCanThinkOf(Exception):
pass
raise AnythingYouCanThinkOf
out = "definitely not `hello world`"
finally:
print(out)
以上导致ValueError: what is this madness?
之前未处理的异常,我们得到No error!!! wowza!
解决方案
推荐阅读
- vbscript - vbscript 不会在 8Mb 之后读取文件
- visual-studio-2019 - Uno 平台 - 在 Visual Studio 扩展管理器中找不到
- java - 使用 Java fileReader 拆分后如何从 CSV 打印数据?
- python-3.x - 如何使用 requests_toolbelt 在 Python 3.7 中编码数据
- python - LDA Topic Modelling : Topics predicted from huge corpus make no sense
- c++ - 为什么调试时程序崩溃但正常(使用代码块)
- c++ - WASM 链接错误:函数签名不匹配
- elasticsearch - 如何在 ELK 中进行实时警报
- vba - 使用 VBA 在 SAP GUI 中查找组件
- c++ - 从函数返回唯一的 void 指针