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模塊,然後引發另一個描述性錯誤。 –