Sometimes, when one creates a custom Python Exception
, one wants to store additional arguments with that exception. The book "Python Cookbook" (2013) then says that one should pass these arguments to the super constructor (i.e. the one of the Exception
class), so that they get stored in the .args
field. They tell us, that various Python libraries expect that, but do not tell us what kind of libraries and what they do with them.
Looking at various Python examples on Github and tutorials on the internet, shows me that storing these additional args is a actually not done very often.
So my question is, where would we actually expect that these args are set? Or was this one the case, but is not anymore? Maybe one reason is so that __str__
shows all arguments, but is that all?
Here is an example custom exception, where I store the arguments val
, lower_bound
and upper_bound
in the constructor, but also pass them to the super constructor, so that they get stored in .args
.
class OutOfBoundsError(Exception):
def __init__(self, val: int, lower_bound: int, upper_bound: int):
msg = f"Value {val} was not in range({lower_bound}, {upper_bound})"
# args appart from msg necessary?
super.__init__(msg, val, lower_bound, upper_bound)
# or maybe storing them as additional fields should be avoided?
self.val = val
self.lower_bound = lower_bound
self.upper_bound = upper_bound