The Python docs state:
Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derivedfrom the Exception class, either directly or indirectly.
...
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.
From Python’s super() considered super!:
Each level strips-off the keyword arguments that it needs so that the final empty dict can be sent to a method that expects no arguments at all (for example, object.init expects zero arguments)
Suppose I have the following StudentValueError
and MissingStudentValue
exceptions.
class StudentValueError(Exception):
"""Base class exceptions for Student Values"""
def __init__(self, message, **kwargs):
super().__init__(**kwargs)
self.message = message # You must provide at least an error message.
class MissingStudentValue(StudentValueError):
def __init__(self, expression, message, **kwargs):
super().__init__(message, **kwargs)
self.expression = expression
def __str__(self):
return "Message: {0} Parameters: {1}".format(self.message, self.expression)
I want to create exceptions that are co-operative. I have two questions:
- In that case, the
Exception
class constructor expects zero arguments (emptydict
), correct? - Does my example violate LSP?
The accepted answer provided here inherits from ValueError
.