This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

User-defined Exceptions

You can also define your own exception classes. To do this, use the mighty power of OOP – you should inherit from the Exception class.

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

You can proceed to use this Exception, 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!")

It is good practice to place all your custom exception classes into a separate file e.g. exceptions.py.

Handling subclasses

Python will match an Exception to the corresponding except clause if it is the same class or a parent/ancestor class.

The example below should explain this clearer.

class SuperClass(Exception):
    pass

class SubClass(SuperClass):
    pass

class SubSubClass(SubClass):
    pass

for cls in [SuperClass, SubClass, SubSubClass]:
    try:
        raise cls()
    except SubSubClass:
        print("SubSubClass")
    except SubClass:
        print("SubClass")
    except SuperClass:
        print("SuperClass")

## SuperClass
## SubClass
## SubSubClass

What happens when we reverse the order of the except clauses? Try to guess, and then check!

for cls in [SuperClass, SubClass, SubSubClass]:
    try:
        raise cls()
    except SuperClass:
        print("SuperClass")
    except SubClass:
        print("SubClass")
    except SubSubClass:
        print("SubSubClass")

Tasks:

  • Try to create your own user-defined Exception class, and another that subclasses your custom class
  • Try to test out where a raised Exception gets matched in an except clause (as above)