Custom Exceptions in Python

Define and raise custom exception classes in an OOP style.

IntermediateObject-Oriented ProgramsExample 20 of 25
custom-exceptions.py
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.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.