繁体   English   中英

未捕获其他模块中定义的python自定义异常

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM