Custom Exceptions in Python

Define and raise custom exception classes in an OOP style.

IntermediateObject-Oriented ProgramsExample 20 of 25
custom-exceptions.py
Run in browser
1# Program to define and use a custom exception
2
3class NegativeAgeError(Exception):
4 pass
5
6def set_age(age):
7 if age < 0:
8 raise NegativeAgeError("Age cannot be negative")
9 print("Age set to", age)
10
11set_age(20)
12# set_age(-5) # would raise NegativeAgeError

Output

Age set to 20

What's going on

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