I would like to declare a hierarchy of custom exceptions in Python. However, I would like my top-level custom class ( TransactionException ) to be abstract. That is, I intend TransactionException to specify the methods that should be defined by its subclasses. However, a TransactionException should never be thrown or thrown.
I have the following code:
from abc import ABCMeta, abstractmethod class TransactionException(Exception): __metaclass__ = ABCMeta @abstractmethod def displayErrorMessage(self): pass
However, the above code allows me to create an instance of TransactionException ...
a = TransactionException()
In this case, a does not make sense, and an exception should be made instead. The following code eliminates the fact that TransactionException is a subclass of Exception ...
from abc import ABCMeta, abstractmethod class TransactionException(): __metaclass__ = ABCMeta @abstractmethod def displayErrorMessage(self): pass
This code correctly prohibits instantiation, but now I cannot raise a subclass of TransactionException because it is no longer an Exception .
Is it possible to define an abstract exception in Python? If so, how? If not, why not?
NOTE. I am using Python 2.7, but would happily agree to respond to Python 2.x or Python 3.x.
source share