Custom Exceptions

Define and raise custom exception classes in an OOP style.

PythonIntermediate
Python
# Program to define and use a custom exception

class NegativeAgeError(Exception):
    pass


def set_age(age):
    if age < 0:
        raise NegativeAgeError("Age cannot be negative")
    print("Age set to", age)


set_age(20)
# set_age(-5)  # would raise NegativeAgeError

Output

Age set to 20

Custom exceptions derive from Exception and add semantic meaning to error conditions.