[英]Is there a way to force an exception to be raised if there is a try catch that catches all exceptions?
I need to force an exception to be raised outside a function that does this:我需要强制在执行此操作的 function 之外引发异常:
def foo(x):
try:
some_calculation(x)
except:
print("ignore exception")
Is there a way to override the catch-all inside foo
?有没有办法覆盖foo
内的全部内容? I would like to raise an exception inside some_calculation(x)
that can be caught or detected outside foo
.我想在some_calculation(x)
中引发一个异常,该异常可以在foo
之外被捕获或检测到。
FYI, foo
is a third party function I have no control over.仅供参考, foo
是第三方 function 我无法控制。
No. Your options are:不,您的选择是:
The last is perhaps the easiest and quickest to get up and running.最后一个可能是最容易和最快的启动和运行。
Example:例子:
# 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
...
Things might be slightly more complicated than that if foo()
is re-exported across several different modules (if the third party library has its own from <x> import foo
statements. But if just requires monkey patching more attributes of the various re-exporting modules.如果foo()
在几个不同的模块中重新导出(如果第三方库有自己的from <x> import foo
语句,那么事情可能会稍微复杂一些。但如果只需要猴子修补各种重新的更多属性 -导出模块。
Technically it would be possible to force an exception to be raised, but it would involve setting an execution trace and forcing an exception to be thrown in the exception handling code of the foo()
.从技术上讲,可以强制引发异常,但这将涉及设置执行跟踪并强制在foo()
的异常处理代码中引发异常。 It would be weird, the exception would appear to come from print("ignore exception")
rather than some_calculation(x)
.奇怪的是,异常似乎来自print("ignore exception")
而不是some_calculation(x)
。 So don't do that.所以不要那样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.