How to Create and Use Custom Exceptions in Python - dummies

How to Create and Use Custom Exceptions in Python

By John Paul Mueller

Python provides a wealth of standard exceptions that you should use whenever possible. These exceptions are incredibly flexible, and you can even modify them as needed (within reason) to meet specific needs.

However, sometimes you simply must create a custom exception because none of the standard exceptions will work. Perhaps the exception name just doesn’t tell the viewer the purpose that the exception serves. You may need a custom exception for specialized database work or when working with a service.

This example shows a quick method for creating your own exceptions. To perform this task, you must create a class that uses an existing exception as a starting point. To make things a little easier, this example creates an exception that builds upon the functionality provided by the ValueError exception.

The advantage of using this approach is that this approach tells anyone who follows you precisely what the addition to the ValueError exception is; additionally, it makes the modified exception easier to use.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    class CustomValueError(ValueError):
     def __init__(self, arg):
      self.strerror = arg
      self.args = {arg}
     raise CustomValueError("Value must be within 1 and 10.")
    except CustomValueError as e:
     print("CustomValueError Exception!", e.strerror)

    This example places the same error in both strerror and args so that the developer has access to either (as would normally happen).

    The code begins by creating the CustomValueError class that uses the ValueError exception class as a starting point. The __init__() function provides the means for creating a new instance of that class. Think of the class as a blueprint and the instance as the building created from the blueprint.

    Notice that the strerror attribute has the value assigned directly to it, but args receives it as an array. The args member normally contains an array of all the exception values, so this is standard procedure, even when args contains just one value as it does now.

    The code for using the exception is considerably easier than modifying ValueError directly. All you do is call raise with the name of the exception and the arguments you want to pass, all on one line.

  3. Choose Run→Run Module.

    You see a Python Shell window open. The application displays the letter sequence, along with the letter number.