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 browser1# 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.