In Python, user-defined exceptions allow for custom error handling by extending the base Exception class. To create one, define a class inheriting from Exception or any of its subclasses. This enables more precise error management and messages, enhancing code readability and debugging efficiency. User-defined exceptions are crucial for signaling specific error conditions in a program.
Prerequisite: Python Exception Handling
User-Defined Exception In Python
User-defined exceptions in Python are a powerful mechanism for creating custom error handling in a program. By inheriting from Python's built-in Exception class, developers can define their own exceptions tailored to their applications' specific needs. This customization allows for more granular error management and clearer, more informative error messages.
For example, consider a scenario where you're building an application that requires a user to input a number within a certain range. You can define a custom exception to handle cases where the input is outside of the allowed range.
class OutOfRangeError(Exception):
def __init__(self, message="Number out of the allowed range"):
self.message = message
super().__init__(self.message)
# Usage
def check_number(number):
if not 1 <= number <= 10:
raise OutOfRangeError("Number must be between 1 and 10")
try:
check_number(15)
except OutOfRangeError as e:
print(e) # Output: Number must be between 1 and 10
Customizing Exception Classes
Customizing exception classes in Python involves defining new exceptions by subclassing the base Exception class or one of its built-in subclasses. This process allows developers to create specific error types for their application's needs, improving error handling and readability.
For instance, you might define a ValidationError class for input validation errors. Here's how you can create and use it.
class ValidationError(Exception):
def __init__(self, message):
self.message = message
# Usage example
def validate_age(age):
if age < 18:
raise ValidationError("Age must be at least 18")
return True
try:
validate_age(16)
except ValidationError as e:
print(f"Error: {e.message}")
Output: Error: Age must be at least 18
User-Defined Class With Multiple Inheritance
User-defined classes with multiple inheritance in Python allow for more versatile exception handling by incorporating characteristics from several parent exceptions. This approach leverages the power of polymorphism, enabling a single exception class to catch errors that would otherwise require multiple catch blocks.
class InputError(ValueError, TypeError):
"""Exception raised for errors in the input."""
def __init__(self, message):
self.message = message
# Usage example
try:
raise InputError("Invalid input")
except InputError as e:
print(e.message)
Output: Invalid input
Deriving Error From Super Class Exception
Deriving error from the super class Exception in Python involves creating custom exceptions by subclassing the Exception class. This technique enhances error handling by enabling developers to define specific error types for their applications, facilitating clearer and more precise debugging.
class ValueTooSmallError(Exception):
"""Exception raised for errors in the input value being too small."""
pass
try:
guess = int(input("Enter a guess: "))
if guess < 10:
raise ValueTooSmallError("The guess is too small")
except ValueTooSmallError as e:
print(e)
Output: The guess is too small
How To Use Standard Exceptions As A Base Class?
To use standard exceptions as a base class in Python, inherit from built-in exception classes to create custom exceptions. This practice allows for leveraging the existing hierarchy of exceptions for more granular error handling. For instance, inheriting from ValueError or TypeError lets you specialize errors related to invalid values or incorrect types, respectively.
class CustomValueError(ValueError):
"""Exception raised for errors in the input value."""
def __init__(self, message="Invalid value provided"):
self.message = message
super().__init__(self.message)
# Usage example
try:
raise CustomValueError("Custom error message")
except CustomValueError as e:
print(e)
Output: Custom error message