Search code examples
pythonoopexceptionpython-module

How to catch an error thrown inside an imported module


I have a custom module with a function, and I am importing it to my main file. When there is an exception raised in the module, I want to catch it in the main file.

Is this possible? I'm having a hard time finding any examples of this online or in the exception documentation.

Example:

exceptionStuff.py

class My_Error(Exception):
    pass

def Fail_Func():
    raise Exception

main.py

from myModules.exceptionStuff import My_Error

try:
    My_Error()
except:
    print('caught')

The exception doesn't get caught here.


Solution

  • If you reorganize exceptionStuff.py like this

    class My_Error(Exception):
        pass
    
    def Fail_Func():
        raise My_Error
    

    And your main file like this

    from exceptionStuff import My_Error, Fail_Func
    
    try:
        Fail_Func()
    except My_Error as e:
        print(e.__class__.__name__)
        print('caught')
    

    You will successfully catch an exception of type My_Error.

    Output:

    My_Error
    caught