Chapter 9: User-defined exceptions

User-defined exceptions

face Josiah Wang

In most cases, you can (and should) just use one of Python’s built-in Exception subclasses from the hierarchy, and pass a custom argument. Just find a semantically related error to use!

You can, however, create your own exceptions when you cannot find a semantically suitable Exception subclass from Python’s list. For example, your own StupidInputError might make your code more self-explanatory, and might be easier to distinguish from the more generic Python exceptions.

Another benefit of creating your own exceptions is that you can use the mighty power of OOP to add custom attributes and methods like you would do for a normal class. This will allow you to do more things with the exceptions. Perhaps you need to keep track of the value of a relevant variable?

class StupidInputError(Exception):
    def __init__(self, input, message="Don't be silly!"):
        self.input = input
        self.message = message

    def print(self):
        print(f"Josiah says: {self.message} You have typed a stupid input: {self.input}")

You can then use these attributes like a normal class instance.

try:
    user_input = input("Please enter a stupid input: ")
    raise StupidInputError(user_input, "You are silly.")
except StupidInputError as err:
    err.print()
    print(err.input)
    print(err.message)

Running this piece of code will output

$ python3 silly_input.py
Please enter a stupid input: hahaha
Josiah says: You are silly. You have typed a stupid input: hahaha
hahaha
You are silly.

I know the example is a bit contrived. But this is just to demonstrate the usefulness of user-defined exceptions (when needed!)