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
raise main.MyException
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
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:)