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