Reference library

Errors & debugging

Handle failures gracefully, raise helpful errors, and debug with confidence.

30 matches
Errors & debugging medium

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.

circuit-breaker resilience error-handling
Python
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")
  …
12 0 Open
Errors & debugging easy

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.

exceptions http-status error-handling
Python
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…
13 0 Open
Errors & debugging easy

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.

eafp lbyl dictionary
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")…
14 0 Open
Errors & debugging easy

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.

retry connection-error error-handling
Python
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…
15 0 Open
Errors & debugging easy

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.

try-except valueerror zerodivisionerror
Python
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…
14 0 Open
Errors & debugging easy

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.

try-except valueerror exception
Python
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…
13 0 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.