Middle
Why might it be necessary to create a custom exception type?
sobes.tech AI
Answer from AI
Creating your own exception type allows:
- To improve code readability and understanding: Exceptions with meaningful names explicitly indicate the nature of the error.
- To provide more granular error handling: You can catch and handle specific error types rather than general
Exception. - To pass additional error information: You can add attributes to your custom exception type to store contextual data.
- To create an error hierarchy: Organize related exceptions into a logical structure, making them easier to handle.
Example:
# Define a custom exception for invalid input
class InvalidInputError(ValueError):
def __init__(self, message, value):
super().__init__(message) # Call the base class constructor
self.value = value # Store the problematic value
# Function that raises the custom exception
def process_input(data):
if not isinstance(data, int):
raise InvalidInputError("Input must be an integer", data) # Raise the custom exception
return data * 2
# Example usage with exception handling
try:
result = process_input("hello")
except InvalidInputError as e:
print(f"Error processing input: {e.message}, value: {e.value}") # Access custom attributes