The simplest way to define a custom error in Python is as follows:
class CustomError(Exception): passThis exception can be raised in any of the following ways:
raise CustomError("This is my error message")
raise CustomError()
raise CustomErrorIt 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