Raising and Handling Custom Exceptions in Python
Python allows you to define and use custom exceptions by subclassing the built-in Exception
class. This is useful when you want to create meaningful, domain-specific error types in your program.
1. Raising a Custom Exception
To raise a custom exception:
- Define a new exception class by inheriting from the
Exception
class (or any subclass ofException
). - Use the
raise
keyword to trigger the exception.
Example:
# Define a custom exception
class CustomError(Exception):
pass
# Raise the custom exception
def risky_function():
raise CustomError("This is a custom exception!")
# Call the function
try:
risky_function()
except CustomError as e:
print(f"Caught an error: {e}")
Output:
Caught an error: This is a custom exception!
2. Adding Additional Attributes
Custom exceptions can include attributes and methods to provide more context about the error.
Example:
class ValidationError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code
try:
raise ValidationError("Invalid input", 400)
except ValidationError as e:
print(f"Error: {e}, Code: {e.code}")
Output:
Error: Invalid input, Code: 400
3. Handling Custom Exceptions
You handle custom exceptions just like any other exception using try-except
.
Example:
class NegativeValueError(Exception):
pass
def check_positive(value):
if value < 0:
raise NegativeValueError("Negative values are not allowed!")
try:
check_positive(-5)
except NegativeValueError as e:
print(f"Error: {e}")
Output:
Error: Negative values are not allowed!
4. Custom Hierarchies of Exceptions
You can define a hierarchy of exceptions for better organization.
Example:
class AppError(Exception):
"""Base class for all application-related errors."""
pass
class DatabaseError(AppError):
pass
class NetworkError(AppError):
pass
try:
raise DatabaseError("Database connection failed!")
except DatabaseError as e:
print(f"Database error: {e}")
except NetworkError as e:
print(f"Network error: {e}")
except AppError as e:
print(f"General app error: {e}")
Output:
Database error: Database connection failed!
5. Combining Custom Exceptions with Standard Exceptions
You can handle custom and standard exceptions together.
Example:
class CustomError(Exception):
pass
try:
x = int("abc") # Raises a ValueError
raise CustomError("Custom error occurred")
except ValueError as e:
print(f"Value error: {e}")
except CustomError as e:
print(f"Custom error: {e}")
Output:
Value error: invalid literal for int() with base 10: 'abc'
Best Practices
- Use meaningful names for custom exceptions to make them self-explanatory.
- Add relevant attributes to pass additional error details.
- Group related exceptions under a common base class for better organization.
- Always use
try-except
to gracefully handle your custom exceptions in the program.
By using custom exceptions effectively, you can improve the readability, maintainability, and robustness of your code.