Table of Contents
ToggleUser-defined exceptions in Python are custom error classes that you create to handle specific error conditions in your code. They are derived from the built-in Exception class or any of its sub classes.
User-defined exceptions provide more precise control over error handling in your application −
To create a user-defined exception, follow these steps −
Create a new class that inherits from the built-in “Exception” class or any other appropriate base class. This new class will serve as your custom exception.
class MyCustomError(Exception): pass
Explanation
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.
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)
Explanation
Override the “__str__” or “__repr__” method to provide a custom string representation of the exception. This is useful for printing or logging the exception.
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}"
Explanation
Once you have defined a custom exception, you can raise it in your code to signify specific error conditions. Raising user-defined exceptions involves using the raise statement, which can be done with or without custom messages and attributes.
Following is the basic syntax for raising an exception −
raise ExceptionType(args)
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 in Python refers to using “try-except” blocks to catch and respond to the specific conditions that your custom exceptions represent. This allows your program to handle errors gracefully and continue running or to take specific actions based on the type of exception raised.
Following is the basic syntax for handling exceptions −
try: # Code that may raise an exception except ExceptionType as e: # Code to handle the exception
In the below example, the “try” block calls “set_age” with an invalid age. The “except” block catches the “InvalidAgeError” and prints the custom error message −
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")
Combining all the steps, here is a complete example of creating and using a user-defined exception −
# Open Compiler
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}")
Output:
Following is the output of the above code −
Invalid age: 150. Age must be between 18 and 100
Key Takeaway: Master user-defined exceptions in Python—create custom errors for precise control—at Vista Academy!
