Custom exceptions in Python are user-defined exceptions created by programmers to handle specific situations that are not clearly represented by Python's built-in exceptions. They are useful when an application has its own rules or conditions that need to be reported as errors. Custom exceptions are usually created by defining a class that inherits from Python's built-in Exception class. In this article, we will learn how to create, raise, and handle custom exceptions in Python with simple examples.
Table of Contents
What are Custom Exceptions in Python?
Custom exceptions are exceptions programmers create to represent specific errors or conditions in an application.- Built-in exceptions: Python provides many built-in exceptions such as ValueError, TypeError, and IndexError. However, these may not always clearly describe a specific application problem.
- Example: An application that manages bank accounts may need a custom InsufficientBalanceError exception when a user tries to withdraw more money than their available balance.
Why Use Custom Exceptions in Python?
Custom exceptions allow programmers to define errors that are specific to their application's needs. They make it easier to identify problems and handle different situations clearly.
- Represent Application-Specific Errors: Custom exceptions can represent errors that are specific to the rules or functionality of a particular application.
- Provide Meaningful Error Messages: They allow programmers to give clear error messages that explain exactly what went wrong.
- Separate Different Application Errors: Custom exceptions make it possible to distinguish between different types of errors that may occur within an application.
- Simplify Exception Handling: They make exception handling easier by allowing specific application errors to be caught and handled separately.
- Improve Code Readability: Using descriptive custom exception names makes the purpose of an error easier to understand when reading the code.
- Make Large Programs Easier to Maintain: Custom exceptions help keep error-handling logic organized, which makes larger programs easier to update and maintain.
How to Create a Custom Exception?
A custom exception can be created by defining a class that inherits from the built-in Exception class.
Syntax:
class CustomError(Exception):
pass
The custom exception can then be raised using the raise statement.
Creating a Simple Custom Exception
The following example creates a simple custom exception called AgeError.
Example:
# Python program to create a simple custom exception
class AgeError(Exception):
pass
age = 15
if age < 18:
raise AgeError("Age must be 18 or above")
Output:
AgeError: Age must be 18 or above
The AgeError class inherits from Exception, making it a custom exception.
Raising a Custom Exception
After creating a custom exception, we can raise it using the raise statement.
Example:
# Python program to demonstrate raising a custom exception
class InvalidMarksError(Exception):
pass
marks = 120
if marks > 100:
raise InvalidMarksError("Marks cannot be greater than 100")
print("Valid marks")
Output:
InvalidMarksError: Marks cannot be greater than 100
The custom exception is raised because the marks are greater than the allowed value.
Handling a Custom Exception
Custom exceptions can be handled using a try-except block.
Example:
# Python program to handle a custom exception
class AgeError(Exception):
pass
try:
age = 16
if age < 18:
raise AgeError("Age must be 18 or above")
except AgeError as error:
print(error)
Output:
Age must be 18 or above
The AgeError exception is raised inside the try block and handled by the except block.
Custom Exception with a Message
A custom exception can receive a message that describes the problem.
Example:
# Python program to demonstrate a custom exception with a message
class PasswordError(Exception):
pass
password_length = 5
try:
if password_length < 8:
raise PasswordError("Password must contain at least 8 characters")
except PasswordError as error:
print(error)
Output:
Password must contain at least 8 characters
The message provides a clear explanation of why the custom exception was raised.
Custom Exception with try-except
Custom exceptions can be used with normal exception-handling structures.
Example:
# Python program to demonstrate custom exception handling
class InsufficientBalanceError(Exception):
pass
balance = 500
withdrawal = 800
try:
if withdrawal > balance:
raise InsufficientBalanceError("Insufficient balance")
balance -= withdrawal
print("Withdrawal successful")
except InsufficientBalanceError as error:
print(error)
Output:
Insufficient balance
The custom exception clearly represents the specific problem in the banking example.
Custom Exception with a Class Constructor
A custom exception can also define its own constructor to store additional information.
Example:
# Python program to demonstrate a custom exception with a constructor
class AgeError(Exception):
def __init__(self, age):
self.age = age
super().__init__(f"Invalid age: {age}. Age must be 18 or above.")
try:
age = 15
if age < 18:
raise AgeError(age)
except AgeError as error:
print(error)
Output:
Invalid age: 15. Age must be 18 or above.
The constructor stores the invalid age and creates a meaningful error message.
Multiple Custom Exceptions
A program can contain multiple custom exception classes for different situations.
Example:
# Python program to demonstrate multiple custom exceptions
class InvalidAgeError(Exception):
pass
class InvalidMarksError(Exception):
pass
try:
age = 20
marks = 120
if age < 18:
raise InvalidAgeError("Age must be 18 or above")
if marks > 100:
raise InvalidMarksError("Marks cannot be greater than 100")
print("Data is valid")
except InvalidAgeError as error:
print(error)
except InvalidMarksError as error:
print(error)
Output:
Marks cannot be greater than 100
Different custom exceptions allow different problems to be handled separately.
Common Beginner Mistakes
- Forgetting to inherit from Exception: A custom exception should normally inherit from Exception or one of its subclasses.
- Using unclear exception names: Choose descriptive names such as AgeError or InsufficientBalanceError so the purpose is clear.
- Creating custom exceptions unnecessarily: Use built-in exceptions when they already describe the problem appropriately.
- Forgetting to handle the custom exception: If the exception is expected to be handled, provide an appropriate try-except block.
- Using unclear error messages: Provide meaningful messages that explain what went wrong and, when useful, how it can be corrected.
Conclusion
Custom exceptions allow Python programmers to create meaningful errors for application-specific situations. They are created by defining classes that inherit from Exception and can be raised using the raise statement. Custom exceptions can also be handled using try-except blocks and can contain additional information when needed. Using custom exceptions appropriately makes Python programs more organized, readable, and maintainable.
Frequently Asked Questions:
1. What are custom exceptions in Python?
Custom exceptions are user-defined exceptions created to represent specific errors or conditions in an application.
2. How do I create a custom exception in Python?
Define a class that inherits from the built-in Exception class.
3. Why are custom exceptions useful?
They make application-specific errors clearer and allow programmers to handle different problems separately.
4. How do I raise a custom exception?
Use the raise statement followed by the custom exception, such as raise AgeError("Invalid age").
5. Can custom exceptions be handled using try-except?
Yes. Custom exceptions can be raised inside a try block and handled using a matching except block.
0 Comments