To create a custom exception in Python, you define a new class that inherits from the built-in
Exceptionclass.You can then trigger it with the
raisekeyword and catch it using a standardtry-exceptblock.
# Basic Custom Exception
# 1. Define the custom exception
class InvalidAgeError(Exception):
pass
# 2. Raise the exception when a condition fails
def check_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative.")
return age
# 3. Catch and handle the exception
try:
check_age(-5)
except InvalidAgeError as e:
print(f"Caught error: {e}")
# Custom Exception with Extra Data
# To attach context like error codes or invalid values, override the __init__ and __str__ methods. Always call super().__init__() so the base Exception class initializes properly.
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 0 and 120."):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.message} (Provided: {self.age})"
try:
raise InvalidAgeError(-5)
except InvalidAgeError as e:
print(e) # Output: Age must be between 0 and 120. (Provided: -5)
print(e.age) # Output: -5