Back
+10 XP
Concept

Creating Custom Exception Classes

Define custom domain exceptions by inheriting from Python's built-in `Exception`: `class AppError(Exception): pass`.

python
class InsufficientFundsError(Exception):
    pass

try:
    raise InsufficientFundsError("Balance is $0")
except InsufficientFundsError as e:
    print(f"Handled custom error: {e}")

# 114. Creating Custom Exception Classes Define custom domain exceptions by inheriting from Python's built-in `Exception`: `class AppError(Exception): pass`: ```python class InsufficientFundsError(Exception): pass try: raise InsufficientFundsError("Balance is $0") except InsufficientFundsError as e: print(f"Handled custom error: {e}") ``` Custom exceptions make your backend architecture modular. Callers can catch `InsufficientFundsError` specifically while letting general `ValueError` or network errors bubble up to logging services.

Checkpoint

What class must your custom error inherit from at minimum?

Practice

Define a custom exception `ServerOfflineError(Exception): pass`. Raise it inside a `try` block and catch it, printing `"Server is down"`.

Terminal
01
Tap code blocks below to assemble
Available Blocks