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 exception
1class AppError(Exception):
# __init__ accepts message and optional error code
2 def __init__(self, message: str, code: int = 500):
# Store message as instance attribute
3 self.message = message
# Store HTTP-style error code
4 self.code = code
# Call parent Exception constructor
5 super().__init__(self.message)
6
# class ValidationError(AppError) for validation failures
7class ValidationError(AppError):
# __init__ takes field name and error message
8 def __init__(self, field: str, message: str):
# Store the field that failed validation
9 self.field = field
# Call parent with formatted message and 400 code
10 super().__init__(f"{field}: {message}", code=400)
11
# class NotFoundError(AppError) for missing resources
12class NotFoundError(AppError):
# __init__ takes resource type and id
13 def __init__(self, resource: str, id: str):
# Store the resource type
14 self.resource = resource
# Store the missing id
15 self.id = id
# Call parent with formatted message and 404 code
16 super().__init__(f"{resource} with id '{id}' not found", code=404)
17
# def process demonstrates raising custom exceptions
18def process(data):
# Check if name field is missing
19 if not data.get("name"):
# Raise validation error for missing name
20 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 exceptions
23try:
# Call process with data missing name
24 process({"id": "123"})
# Catch any AppError or its subclasses
25except AppError as e:
# Print error with code and message
26 print(f"Error [{e.code}]: {e.message}")

Output

Error [400]: name: is required
Practice typing this code

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

More Python examples at level 5

← Python typing practice