2017-07-18 56 views
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 
+1

你可以在'sys.excepthook'看一看:https://docs.python.org/3/library/sys.html#sys.excepthook 编辑:你的动机是什么? – jackarms

+0

对于这样的机制,在异常处理后恢复执行的地方还不清楚。尝试在抛出异常的位置恢复执行,历史上会导致可怕的错误操作,而且几乎没有人设计异常处理系统。 – user2357112

+0

@jackarms OpenCV的Python API有非常不明确的错误。我想创建一个捕捉错误的简单Python模块,然后引发另一个描述性错误。 –

回答

0

可以通过创建一个上下文管理器完成的,但它在一个明确的try:except:给可疑的好处。你将不得不使用with声明,所以它将清楚行为会改变的地方。在这个例子中,我使用contextlib.contextmanager来做到这一点,这节省了用__enter____exit__方法创建类的繁琐操作。

from contextlib import contextmanager 

@contextmanager 
def IgnoreNameErrorExceptions(): 
    """Context manager to ignore NameErrors.""" 
    try: 
     yield 
    except NameError as e: 
     print(e) # You can print whatever you want here. 

with IgnoreNameErrorExceptions(): 
    print(this_variable_is_not_defined) 

这将输出

name 'this_variable_is_not_defined' is not defined 
相关问题