[英]How can I write a `try`/`except` block that catches all exceptions?
[英]Is there a way to force an exception to be raised if there is a try catch that catches all exceptions?
我需要强制在执行此操作的 function 之外引发异常:
def foo(x):
try:
some_calculation(x)
except:
print("ignore exception")
有没有办法覆盖foo
内的全部内容? 我想在some_calculation(x)
中引发一个异常,该异常可以在foo
之外被捕获或检测到。
仅供参考, foo
是第三方 function 我无法控制。
不,您的选择是:
最后一个可能是最容易和最快的启动和运行。
例子:
# before doing anything else import and patch the third party library
# we need to patch foo before anyone else has a chance to import or use it
import third_party_library
# based off of third_party_library version 1.2.3
# we only catch Exception rather than a bare except
def foo(x):
try:
some_calculation(x)
except Exception:
print("ignore exception")
third_party_library.foo = foo
# rest of program as usual
...
如果foo()
在几个不同的模块中重新导出(如果第三方库有自己的from <x> import foo
语句,那么事情可能会稍微复杂一些。但如果只需要猴子修补各种重新的更多属性 -导出模块。
从技术上讲,可以强制引发异常,但这将涉及设置执行跟踪并强制在foo()
的异常处理代码中引发异常。 奇怪的是,异常似乎来自print("ignore exception")
而不是some_calculation(x)
。 所以不要那样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.