Question
Why do virtual subclasses of an abstract Exception
created using the ABCMeta.register
not match under the except
clause?
Background
I'd like to ensure that exceptions that get thrown by a package that I'm using are converted to MyException
, so that code which imports my module can catch any exception my module throws using except MyException:
instead of except Exception
so that they don't have to depend on an implementation detail (the fact that I'm using a third-party package).
Example
To do this, I've tried registering an OtherException
as MyException
using an abstract base class:
# Tested with python-3.6
from abc import ABC
class MyException(Exception, ABC):
pass
class OtherException(Exception):
"""Other exception I can't change"""
pass
MyException.register(OtherException)
assert issubclass(OtherException, MyException) # passes
try:
raise OtherException("Some OtherException")
except MyException:
print("Caught MyException")
except Exception as e:
print("Caught Exception: {}".format(e))
The assertion passes (as expected), but the exception falls to the second block:
Caught Exception: Some OtherException