Custom Exception Hierarchy in Python
Level 5284 keystrokes
This creates a custom exception hierarchy with base and derived classes. Custom attributes like error codes enhance error handling.
Python code
# Define base exception class inheriting from Exception1class AppError(Exception): # Constructor takes message and error code2 def __init__(self, message, code): # Call parent constructor with message3 super().__init__(message) # Store error code as attribute4 self.code = code5 # Define validation error subclass6class ValidationError(AppError): # Inherits everything from AppError7 pass8 # Define database error subclass9class DatabaseError(AppError): # Inherits everything from AppError10 pass11 # Try block to test exception12try: # Raise validation error with message and code13 raise ValidationError("Invalid input", 400)# Catch any AppError or its subclasses14except AppError as e: # Print formatted error with code and message15 print(f"Error [{e.code}]: {e}")Output
Error [400]: Invalid input
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 8(× 8)× 8:× 7"× 4,× 3.× 3{× 2}× 2[× 1