Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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")
…
Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
EXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_S…
Python dict try-except KeyError EAFP vs LBYL
Compare EAFP (try-except) and LBYL (if-in-check) styles for safely accessing dictionary keys, with working examples in Python.
def safe_get_lbyl(d, key):
if key in d:
return d[key]
return "default-lbyl"
def safe_get_eafp(d, key):
try:
return d[key]
except KeyError:
return "default-eafp"
if __name__ == "__main__":
data = {"name": "Alice", "age": 30}
print("LBYL:", safe_get_lbyl(data, "missing")…
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…
Split try except ValueError handler for beginners in Python
Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.
def parse_number(text):
try:
number = int(text)
return f"Parsed successfully: {number}"
except ValueError as error:
return f"Conversion failed: {error}"
def divide_numbers(dividend, divisor):
try:
result = dividend / divisor
return f"Division result: {result}"
e…
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.