0
是否有东西,我可以用来捕获python中的错误,而不使用try/except?如何在不使用try/except的情况下捕获错误?
我在想是这样的:
main.py
from catch_errors import catch_NameError
print(this_variable_is_not_defined)
catch_errors.py
def catch_NameError(error):
if type(error) == NameError:
print("You didn't define the error")
输出将是:
You didn't define the error
相反的:
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(this_variable_is_not_defined)
NameError: name 'this_variable_is_not_defined' is not defined
你可以在'sys.excepthook'看一看:https://docs.python.org/3/library/sys.html#sys.excepthook 编辑:你的动机是什么? – jackarms
对于这样的机制,在异常处理后恢复执行的地方还不清楚。尝试在抛出异常的位置恢复执行,历史上会导致可怕的错误操作,而且几乎没有人设计异常处理系统。 – user2357112
@jackarms OpenCV的Python API有非常不明确的错误。我想创建一个捕捉错误的简单Python模块,然后引发另一个描述性错误。 –