[英]python custom exception defined in other module is not caught
讓我總結一下:
我有一個包含兩個類的模塊(注意:這個模塊在一個包中):
自定義異常:
class MYAUTHError(Exception):
def __init__(self, *args, **kwargs):
print('--- MYAUTHError!!! ---')
和一個使用這個異常的類(這里是一個示例):
try:
resp_login.raise_for_status()
except requests.exceptions.HTTPError as ex:
logging.error("ERROR!!! : user authentication failed)
raise MYAUTHError('oups')
在這個模塊(文件)中,我知道這是有效的。 例如,我可以編寫這樣的代碼並驗證我的自定義異常是否被捕獲:
try:
raise MYAUTHError('oups')
except MYAUTHError:
print("got it")
但是,當從另一個模塊(導入該模塊的模塊)使用時,我沒有成功捕獲這個自定義異常......
from mypackage import mymodulewithexception
# somewhere in the code, just to test. OK : my class is known.
extest = mymodulewithexception.MYAUTHError('**-test-**')
print(type(extest))
# but this does not catch anything :
except mymodulewithexception.MYAUTHError as ex:
logging.error("Authentication failed", ex)
return
我敢肯定,拋出異常,因為調用模塊是一個燒瓶應用程序,調試服務器清楚地向我顯示拋出異常是因為它沒有被處理。
在試圖理解這一點時,我只是用另一個著名的異常替換了我的自定義異常:ValueError。 我更改了調用模塊中的代碼以捕獲此內容:當然,這有效。
我什至嘗試過,只捕獲一個異常(真正的通用類):
except mymodulewithexception.MYAUTHError as ex:
print("got it")
except Exception as ex:
print('----------------------------------------------------')
print(ex)
print('-------------------')
我的自定義異常在第一個捕獲中被忽略,但在第二個捕獲中被捕獲...
我的自定義異常怎么可能沒有被正確捕獲? 也許,包上下文?
感謝您的幫助!
通過嘗試在一個小例子中重現,我意識到它來自我的模塊組織......編輯:在包內導入模塊的錯誤方法
讓我們用一個例子來總結:有 2 個包(pack1 和 pack2)。 文件系統上的組織是這樣的:
a_directory
|
|--pack1
| |-- __init__.py
| |-- mymodulewithexception.py
| |-- inheritclass.py
|
|--pack2
|-- __init__.py
|-- callerModule.py
pack1.mymodulewithexception.py :
class MYAUTHError(Exception):
def __init__(self, *args, **kwargs):
print('--- MYAUTHError!!! ---')
class UseMyAUTH:
def testEx(self):
print("I am going to user your custom exception!")
raise MYAUTHError('oups')
pack1.inheritclass.py :
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path)
from mymodulewithexception import UseMyAUTH
class BlablaClass(UseMyAUTH):
pass
編輯:這種在 pack1.inheritclass.py 中導入模塊的方式是錯誤的
編輯:相反:
from .mymodulewithexception import UseMyAUTH
class BlablaClass(UseMyAUTH):
pass
pack2.callerModule.py
from pack1 import mymodulewithexception, inheritclass
blabla = inheritclass.UseMyAUTH()
try:
blabla.testEx()
except mymodulewithexception.MYAUTHError:
print('Catched')
我是這樣運行的:
d:\a_directory> python -m pack2.callerModule
它拋出但沒有“攔截”的異常:
mymodulewithexception.MYAUTHError: oups
編輯:現在它起作用了!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.