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 Exception
1class AppError(Exception):
# Constructor takes message and error code
2 def __init__(self, message, code):
# Call parent constructor with message
3 super().__init__(message)
# Store error code as attribute
4 self.code = code
5
# Define validation error subclass
6class ValidationError(AppError):
# Inherits everything from AppError
7 pass
8
# Define database error subclass
9class DatabaseError(AppError):
# Inherits everything from AppError
10 pass
11
# Try block to test exception
12try:
# Raise validation error with message and code
13 raise ValidationError("Invalid input", 400)
# Catch any AppError or its subclasses
14except AppError as e:
# Print formatted error with code and message
15 print(f"Error [{e.code}]: {e}")

Output

Error [400]: Invalid input
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.

  • _× 8
  • (× 8
  • )× 8
  • :× 7
  • "× 4
  • ,× 3
  • .× 3
  • {× 2
  • }× 2
  • [× 1

More Python examples at level 5

← Python typing practice