Custom Exception Hierarchy in Python
Level 5714 keystrokes
This creates a custom exception hierarchy with base AppError and specialized subclasses.
Python code
# class AppError(Exception) is the base custom exception1class AppError(Exception): # __init__ accepts message and optional error code2 def __init__(self, message: str, code: int = 500): # Store message as instance attribute3 self.message = message # Store HTTP-style error code4 self.code = code # Call parent Exception constructor5 super().__init__(self.message)6 # class ValidationError(AppError) for validation failures7class ValidationError(AppError): # __init__ takes field name and error message8 def __init__(self, field: str, message: str): # Store the field that failed validation9 self.field = field # Call parent with formatted message and 400 code10 super().__init__(f"{field}: {message}", code=400)11 # class NotFoundError(AppError) for missing resources12class NotFoundError(AppError): # __init__ takes resource type and id13 def __init__(self, resource: str, id: str): # Store the resource type14 self.resource = resource # Store the missing id15 self.id = id # Call parent with formatted message and 404 code16 super().__init__(f"{resource} with id '{id}' not found", code=404)17 # def process demonstrates raising custom exceptions18def process(data): # Check if name field is missing19 if not data.get("name"): # Raise validation error for missing name20 raise ValidationError("name", "is required") # Only reached when name is present (here, for demonstration)21 raise NotFoundError("User", data.get("id", "unknown"))22 # try block to catch custom exceptions23try: # Call process with data missing name24 process({"id": "123"})# Catch any AppError or its subclasses25except AppError as e: # Print error with code and message26 print(f"Error [{e.code}]: {e.message}")Output
Error [400]: name: is required
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.
_× 24"× 22:× 19(× 19)× 19.× 13,× 11=× 8{× 7}× 7