2017-07-18 80 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 
相關問題