Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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 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 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")
…
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.