Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
Catch RecursionError and Fail Gracefully in Python
Wrap a recursive function call in a try-except block to catch RecursionError and print a graceful failure message instead of crashing.
def compute_factorial_recursive(n):
"""Compute factorial recursively, raising RecursionError for deep recursion."""
if n == 0:
return 1
return n * compute_factorial_recursive(n - 1)
if __name__ == "__main__":
try:
result = compute_factorial_recursive(10000)
print(f"Factorial c…
Catch ValueError and print friendly message in Python
Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.
try:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
Collect Multiple Validation Errors in Python Before Raising
A chainable Validator class that accumulates all validation errors and raises them together in a single exception.
class ValidationError(Exception):
pass
class Validator:
def __init__(self):
self.errors = []
def validate_required(self, value, field_name):
if not value:
self.errors.append(f"{field_name} is required")
return self
def validate_email(self, email):
…
How to Assert Preconditions with Descriptive Messages in Python
Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.
def divide(dividend, divisor):
assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
return dividend / divisor
if __name__ == "__main__":
print(divide(10, 2))
try:
divide(10, 0)
except AssertionError as e:
print(f"AssertionError: {e}")
How to Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Mock a Failing Dependency to Test Error Paths in Python
Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.
import requests
def fetch_user(user_id):
url = f"https://api.example.com/users/{user_id}"
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
def get_user_name(user_id, http_client):
try:
user_data = http_client(user_id)
return user_data["nam…
How to Print an Exception Chain in Python for Debugging
A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.
import sys
import traceback
def pretty_exception_chain(exc):
"""Print the full exception chain with cause/context details."""
chain = []
current = exc
seen = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
chain.append(current)
curren…
How to Raise a Custom Exception with Extra Context in Python
Define a custom exception that carries extra context fields and raise it to provide richer error information.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")
def withdraw(balance, amount):
if amount > balance:
raise Insuffici…
How to Re-raise Exceptions with 'raise from' in Python
Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.
def divide_with_chain(a, b):
try:
result = a / b
return result
except ZeroDivisionError as original_error:
# Re-raise with explicit chaining context
raise ValueError("Cannot divide by zero") from original_error
def explain_chain():
try:
divide_with_chain(10, 0)
…
How to Simulate Timeout with Custom TimeoutError in Python
Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TimeoutError(Exception):
"""Raised when an operation exceeds its time limit."""
def __init__(self, message: str = "Operation timed out"):
self.message = message
super().__init__(self.message)
def run_with_timeout(func…
How to Test Exceptions in Python with pytest.raises
Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.
import pytest
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero_raises():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
def test_divide_by_zero_raises_exact_match():
with py…
How to Use Optional Return in Python Instead of Raising Exceptions
A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.
from typing import Optional
def find_user(users: dict, user_id: int) -> Optional[dict]:
"""
Look up a user by ID. Returns the user dict if found,
otherwise returns None instead of raising KeyError.
"""
return users.get(user_id)
def main() -> None:
users = {
1: {"name": "Alice", "ema…
How to Use a Fallback Path with FileNotFoundError in Python
Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.
import pathlib
def read_config(path):
primary = pathlib.Path(path)
fallback = pathlib.Path("config_backup.json")
try:
with primary.open("r") as f:
return f.read()
except FileNotFoundError:
try:
with fallback.open("r") as f:
return f.read()
…
How to Validate Input and Raise TypeError in Python
Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.
def validate_number(value):
if not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__}")
return value * 2
if __name__ == "__main__":
try:
print(validate_number(5))
print(validate_number("hello"))
except TypeError as e:
print(…
How to Validate JSON in Python and Catch JSONDecodeError
A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.
import json
def validate_json(json_string):
"""Try to parse JSON, return (is_valid, data_or_error)."""
try:
data = json.loads(json_string)
return True, data
except json.JSONDecodeError as e:
return False, f"Invalid JSON: {e}"
if __name__ == "__main__":
test_inputs = [
…
How to Validate an Email Address and Raise ValueError in Python
This code defines a validate_email function that checks an email address against a regex pattern and several rules, raising ValueError with a specific reason when invalid.
import re
def validate_email(email: str) -> str:
"""Validate an email address and return it if valid, otherwise raise ValueError."""
if not isinstance(email, str):
raise ValueError("Email must be a string")
if len(email) > 254:
raise ValueError("Email length exceeds 254 characters")
#…
How to Wrap a Low Level Error in a Higher Level Exception in Python
Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.
class LowLevelError(Exception):
pass
class HighLevelError(Exception):
pass
def low_level_operation():
raise LowLevelError("storage drive failed to respond")
def high_level_operation():
try:
low_level_operation()
except LowLevelError as e:
raise HighLevelError(f"database operation…
How to check for None and raise helpful errors in Python
A defensive function that explicitly validates data, keys, and values — raising descriptive ValueError and KeyError exceptions before returning a result.
def get_value(data, key):
if data is None:
raise ValueError("data cannot be None")
if key not in data:
raise KeyError(f"key '{key}' not found in data")
result = data[key]
if result is None:
raise ValueError(f"value for key '{key}' is None")
return result
if __name__ == "__…
How to define an exception hierarchy for domain errors in Python
Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.
class DomainError(Exception):
"""Base class for all domain errors."""
pass
class ValidationError(DomainError):
"""Raised when input data fails validation rules."""
pass
class NotFoundError(DomainError):
"""Raised when a requested entity does not exist."""
pass
class PermissionDeniedError(Dom…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
Try Except ValueError in Python: Handle Conversion Errors
Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.
def convert_to_int(value):
try:
return int(value)
except ValueError as error:
print(f"Conversion failed: {error}")
print(f"Problem value was: {repr(value)}")
return None
def divide_numbers(numerator, denominator):
try:
result = numerator / denominator
retur…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.