Skip to content

Instantly share code, notes, and snippets.

@jakelevi1996
Last active June 25, 2021 11:54
Show Gist options
  • Select an option

  • Save jakelevi1996/a58bae3578c583dc460b080992877f9d to your computer and use it in GitHub Desktop.

Select an option

Save jakelevi1996/a58bae3578c583dc460b080992877f9d to your computer and use it in GitHub Desktop.
Custom exceptions in Python

Custom exceptions in Python

The simplest way to define a custom error in Python is as follows:

class CustomError(Exception): pass

This exception can be raised in any of the following ways:

raise CustomError("This is my error message")
raise CustomError()
raise CustomError

It is possible to pass an error message to the constructor along with other arguments, or to set a constant error message for the exception, by calling the constructor of the parent class, as described in this Stack Overflow answer:

class CustomError2(Exception):
    def __init__(self):
        super().__init__(
            "Custom error message "
            "which spans multiple lines"
        )

This exception can be raised in either of the following ways, with the custom error message being printed to the console:

raise CustomError2()
raise CustomError2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment