Custom exception handling in Python

I have two modules: main and notmain. I have declared my usual exception in the main module and want to catch it. This exception occurs in the notmain module. The problem is that I cannot catch my exception raised in the notmain module.

main.py:

class MyException(Exception):
    pass

m = __import__('notmain')
try:
    m.func()
except MyException as e:
    print(type(e))
    print('ops')

notmain.py:

def func():
    import main # 1
    # from main import MyException # 2
    # from main import MyException as MyException # 3

    raise main.MyException # 1
    # raise MyException # 2, 3

I tried different import methods with the same result. When I run main.py, I see the following:

<class 'main.MyException'>
ops
Traceback (most recent call last):
  File "D:\exception\main.py", line 6, in <module>
    m.func()
  File "D:\exception\notmain.py", line 6, in func
    raise main.MyException # 1
main.MyException

This means the exception is somehow caught, but why am I seeing a trace? And why is the exception class named "main.MyException"?

Now, if I changed main.py a bit and ran it:

try:
    raise MyException
except MyException as e:
    print(type(e))
    print('ops')

I will see what is expected:

<class '__main__.MyException'>
ops

I do not know why this MyException class has different names in main.py and notmain.py? And why can't Python catch it as expected?

Thanks:)

+3
2

main ( main __main__), MyException. , .

+8

__main__, , . ( , , "" ).

, notmain - . " notmain import func"?

+1

Source: https://habr.com/ru/post/1721996/