Skip to content

Python custom exception best practices

  • by

Generally, the Best practice is to define a custom exception for your module in Python. E.g custom exceptions can be very useful if complex or specific information needs to be stored in exception instances

class MyException(Exception):
    pass

To override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):            
        # Call the base class constructor with the parameters it needs
        super().__init__(message)
            
        # Now for your custom code...
        self.errors = errors

That way you could pass a dict of error messages to the second param, and get to it later with e.errors.

In Python 2, you have to use this slightly more complex form of super():

super(ValidationError, self).__init__(message)

Source: https://stackoverflow.com/questions/1319615/

Python custom exception best practices

Simple example code.

class NoMoreExcep(Exception):
    """A flexible reminder to go to the store.
       Can be called with a full string or with "what" parameter to get a default message, e.g.
           NoMoreExcep("We're out of polar ice caps. Bring a boat.")
           NoMoreExcep(what="cheese")"""


def __init__(self, message=None, what=None):
    if what is not None:
        msg = f"We're out of {what}."
    elif message is None:
        msg = "An inconsiderate colleague ran out of something.  Go look in the source; he hates you."
    else:
        msg = message
    super(NoMoreExcep, self).__init__(msg)


ex1 = NoMoreExcep("We're out of coffee! Development work cannot continue!!!")
ex2 = NoMoreExcep(what=["apple juice", "Pop Tarts"])

print(repr(ex1))
print(repr(ex2))

# Don't do this:
bad = NoMoreExcep()
print(repr(bad))

Output:

Python custom exception best practices
  • Errors that must be handled the same way should be in the same class.
  • Errors that you don’t see a good reason to handle separately can be the same class until you find a reason.
  • Errors that a user might sometimes have good reason to distinguish should be distinct classes.
    • If one error is a special case of a more general error that you have, make the former a subclass of the latter.
    • If they’re just different errors, don’t have a subclass relationship between them.

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading