7

Let me sum up :

I have a module containing two classes (note : this module is in a package) :

a custom Exception :

class MYAUTHError(Exception):
    def __init__(self, *args, **kwargs):
        print('--- MYAUTHError!!! ---')

and a class using this exception (here a sample) :

try:
    resp_login.raise_for_status()
except requests.exceptions.HTTPError as ex:
    logging.error("ERROR!!! : user  authentication failed)
    raise MYAUTHError('oups')

Inside this module (file) i know this works. For exemple, I can code things like this and verify that my custom exception is caught :

try:
    raise MYAUTHError('oups')
except MYAUTHError:
    print("got it")

However, when used from another module (a module importing this module), I do not succeed catching this custom exception...

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

I'm sure, the exception is thrown, because the calling module is a flask app and the debug server clearly show me the exception is thrown because it is not handled.

While trying to understand this, I simply replaced my custom exception with another famous exception : ValueError. I change code in the calling module to catch this : This worked, of course.

I even tried, to just catch a Exception (the really generic class) :

   except mymodulewithexception.MYAUTHError as ex:
        print("got it")
   except Exception as ex:
        print('----------------------------------------------------')
        print(ex)
        print('-------------------')

My custom exception is ignored in the first catch, but caught on the second one...

How can it be my custom exception is not caught properly? Perhaps, the package context?

Thanks for your help!

stockersky
  • 1,531
  • 2
  • 20
  • 36

1 Answers1

3

By trying to reproduce in a small example, I realized that it comes from my module organization... EDIT : And a wrong way to import module inside a packlage

Let sum up with a example : there are 2 packages (pack1 and pack2). The organization on filesystem is this :

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

EDIT : this way of importing module in pack1.inheritclass.py is wrong

EDIT : instead :

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')

I run it this way :

d:\a_directory>  python -m pack2.callerModule

Exception it thrown but not 'intercepted' :

mymodulewithexception.MYAUTHError: oups

EDIT : and now it works!!!

santo
  • 418
  • 1
  • 3
  • 13
stockersky
  • 1,531
  • 2
  • 20
  • 36
  • 2
    While this question was asked over one year, I do want to comment something to let other people who found this page avoid any misunderstandings for the OP's question, if I am right, the problem is originated from the **relative** and **absolute** `import`, for more detail discussion, please refer [link_1](https://www.python.org/dev/peps/pep-0328/), [link_2](https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html), [link_3](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). Anyway, this is still a good example to handle `Exceptioin`s. – Xiang Jan 07 '19 at 20:24