Mar-18-2019, 06:08 PM
The Python docs state:
For example:
I fixed it like this:
I can now create an instance of
Have I created a custom exception that doesn't violate LSP, co-operates, and is considered best practice?
Quote:Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.
For example:
class StudentValueError(Exception): pass
Quote:When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:
class MissingStudentValueError(StudentValueError): def __init__(self, expression, error_message): self.error_message = error_message self.expression = expression # expression that raise the exception.2 problems, it doesn't co-operate, and it violates LSP (I can't create an instance of
MissingStudentValueError
with zero arguments, like I can with just Exception
alone). I fixed it like this:
class StudentValueError(Exception): """Base class exceptions for Student Values""" def __init__(self, *args): super().__init__(*args) class MissingStudentValue(StudentValueError): def __init__(self, expression="", error_message="", *args): super().__init__(*args) self.error_message = error_message self.expression = expression # expression that raise the exception. def __str__(self): return "Message: {0} Parameters: {1}".format(self.error_message, self.expression)I reached out to Yury Selivanov, a Python Core Developer and he stated:
Quote:Calling "super().__init__(*args)" is the exactly right approach.
I can now create an instance of
MissingStudentValue
without any arguments, and the subclass takes whatever arguments are necessary, and the rest is passed up the call chain to the base class Exception
.Have I created a custom exception that doesn't violate LSP, co-operates, and is considered best practice?