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 exception23class NegativeAgeError(Exception):4 pass56def set_age(age):7 if age < 0:8 raise NegativeAgeError("Age cannot be negative")9 print("Age set to", age)1011set_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.