Chapter 9: User-defined exceptions

User-defined exceptions

face Josiah Wang

Since you have learnt the power of inheritance, you might have realised that you can actually define your own Exception classes.

You should typically derive your custom exception from Exception (or any of its subclasses). PEP 8 also recommends that you add the word Error to the end of your exception’s name, e.g. InvalidInputError.

In its most basic form, you just create a class as normal, with Exception (or any of its subclasses) as its superclass.

class StupidInputError(Exception):
    """ Raised when a user enters a stupid input. """
    pass

You can then proceed to use this StupidInputError, for example like this (not the best example of EAFP, I know!)

try:
    user_input = input("Don't enter 'python': ")
    if user_input.lower() == "python":
        raise StupidInputError()
except StupidInputError:
    print("I told you not to enter 'python'. That's taboo!")