User Defined Exceptions:
User defined exceptions in python are created by programmers to enforce constraints on
the values of the variables in the program can take.
They are derived from the built-in Exception class.
Exceptions need to be derived from the Exception class, either directly or indirectly.
Although not mandatory, most of the exceptions are named as names that end in “Error”
In Python, we can define custom exceptions by creating a new class that is derived from
the built-in Exception class.
How to Create a User-Defined Exception:
Step 1 − Define the Exception Class
Create a new class that inherits from the built-in "Exception" class This new class will
serve as your custom exception.
Ex:
class MyCustomError(Exception):
pass
Step 2 − Initialize the Exception
Implement the "__init__" method to initialize any attributes or provide custom error
messages. This allows you to pass specific information about the error when raising the
exception.
Ex:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
Step 3 − Optionally Override "__str__" or "__repr__"
Override the "__str__" or "__repr__" method to provide a custom string representation of
the exception. This is useful for printing or logging the exception.
Ex:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.message}. Provided age: {self.age}"
Raising User-Defined Exceptions:
Once a custom exception is created, we can raise it in code to signify specific error
conditions. Raising user-defined exceptions involves using the raise statement
Syntax:
raise ExceptionType(args)
Ex:
In this example, the "set_age" function raises an "InvalidAgeError" if the age is outside
the valid range .
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
Handling User-Defined Exceptions:
Handling user-defined exceptions in Python refers to using "try-except" blocks to catch
and respond to the specific conditions that custom exceptions represent.
This allows program to handle errors gracefully
Syntax:
try:
# Code that may raise an exception
except ExceptionType as e:
# Code to handle the exception
Ex:
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")
In the above example, the "try" block calls "set_age" with an invalid age. The "except"
block catches the "InvalidAgeError" and prints the custom error message .
EXAMPLE:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.message}. Provided age: {self.age}"
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")