Custom Exceptions
Define and raise custom exception classes in an OOP style.
IntermediateTopic: Object-Oriented Programs
Python Custom Exceptions Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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 NegativeAgeErrorOutput
Age set to 20
Understanding Custom Exceptions
Custom exceptions derive from Exception and add semantic meaning to error conditions.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.