0

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
Simon Schoelly
  • 697
  • 5
  • 11
  • 1
    Practice has changed over time. You say you are asking about 3.x, but relatively few people even used 3.x when the book was written. That said, `.args` means there's one specific place where generic arguments can be stored for exceptions, and where exception handling code can expect to find information about the error (rather than having to *parse* the information as a string). "They tell us, that various Python libraries expect that" Well, how often does library code call *your* code, and then consider that it could raise an exception? Usually it's the other way around.... – Karl Knechtel Jan 16 '23 at 06:51

0 Answers0