Reference library

Errors & debugging

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

59 matches
Errors & debugging easy

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.

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

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.

error handling try except valueerror
Python
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")
13 0 Open
Errors & debugging medium

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.

validation exceptions errors
Python
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):
        …
14 0 Open
Errors & debugging easy

Handle ValueError and ZeroDivisionError in Python with try except

Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.

try-except valueerror zerodivisionerror
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ValueError as e:
        print(f"ValueError caught: {e}")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    return result

# Test cases
print(safe_divide…
12 0 Open
Errors & debugging medium

How to Add a Correlation ID to Logging Records in Python

Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.

logging correlation-id filter
Python
import logging
import uuid
from dataclasses import dataclass, field


@dataclass
class CorrelationIdFilter(logging.Filter):
    correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))

    def filter(self, record: logging.LogRecord) -> bool:
        record.correlation_id = self.correlation_id
        re…
15 0 Open
Errors & debugging easy

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.

assert debugging preconditions
Python
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}")
16 0 Open
Errors & debugging easy

How to Assert an Invariant After a Complex Transformation in Python

Use assert to verify that a multi-step transformation preserves a mathematical invariant, catching regressions early.

assert debugging invariants
Python
def transform_value(value):
    """Apply several transformations to a value."""
    doubled = value * 2
    shifted = doubled + 10
    normalized = shifted / 2
    return int(normalized)

def assert_invariant(value):
    """Assert that the transformation preserves a key invariant."""
    original = value
    transform…
13 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
Errors & debugging easy

How to Build an Error Code Enum in Python

Define an API error code enum with descriptions and build structured error payloads for HTTP responses.

enum error-handling api
Python
from enum import Enum

class APIErrorCode(Enum):
    SUCCESS = 0
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    FORBIDDEN = 403
    NOT_FOUND = 404
    CONFLICT = 409
    INTERNAL_ERROR = 500


def describe_error(code):
    descriptions = {
        APIErrorCode.SUCCESS: "Request completed successfully",
        APIE…
11 0 Open
Errors & debugging easy

How to Catch KeyError with a Default Value in Python Dictionaries

Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.

keyerror dictionary error-handling
Python
def get_value(data, key, default=None):
    """
    Safely get a value from a dictionary, returning a default if the key
    is missing or the value is None.
    """
    try:
        value = data[key]
        return value if value is not None else default
    except KeyError:
        return default


if __name__ == "_…
14 0 Open
Errors & debugging easy

How to Catch ValueError in Python

Shows how to handle a ValueError with try-except so a bad int() conversion doesn't crash the script.

try-except valueerror error-handling
Python
try:
    number = int("not_a_number")
    print(f"Parsed successfully: {number}")
except ValueError as e:
    print(f"Error: {e}")
    print("Please provide a valid integer.")
print("Program continues running.")
16 0 Open
Errors & debugging easy

How to Catch ValueError in Python (try except)

Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.

errors exception handling valueerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed number: {number}"
    except ValueError as error:
        return f"Error: '{text}' is not a valid number ({error})"


if __name__ == "__main__":
    examples = ["42", "hello", "3.14", "100"]
    for item in examples:
        print(pars…
11 0 Open
Errors & debugging easy

How to Configure Python Logging with File Rotation

A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.

logging file-handler rotating-file-handler
Python
import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)

file_handler = RotatingFileHandler(
    "app.log",
    maxBytes=100,
    backupCount=3
)
file_handler.setFormatter(
    logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
13 0 Open
Errors & debugging easy

How to Debug Print Behind a DEBUG Environment Flag in Python

Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.

debugging environment-variables logging
Python
import os


def debug_print(*args, **kwargs):
    """Print only when DEBUG environment variable is set to a truthy value."""
    if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
        print(*args, **kwargs)


if __name__ == "__main__":
    # Example usage: run as `DEBUG=1 python script.py` to se…
11 0 Open
Errors & debugging easy

How to Detect the Recursion Limit in Python with sys.getrecursionlimit

This Python code recursively calls itself, printing the current recursion depth and the recursion limit from sys.getrecursionlimit, and catches the RecursionError when the limit is hit.

recursion sys debugging
Python
import sys

def recurse(depth=0):
    print(f"Depth: {depth}, Recursion limit: {sys.getrecursionlimit()}")
    return recurse(depth + 1)

if __name__ == "__main__":
    try:
        recurse()
    except RecursionError:
        print("Recursion limit reached!")
        print(f"Final recursion limit: {sys.getrecursionli…
13 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Errors & debugging easy

How to Emit Deprecation Warnings in Python

Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.

warnings deprecation debugging
Python
import warnings


class OldAPI:
    def __init__(self):
        warnings.warn(
            "OldAPI is deprecated; use NewAPI instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.data = []

    def add(self, item):
        warnings.warn(
            "OldAPI.add() is deprecated; us…
14 0 Open
Errors & debugging easy

How to Handle ValueError Exceptions in Python

A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.

exceptions valueerror try-except
Python
def divide_numbers(a, b):
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Please provide numbers, not strings."
    except ValueError:
        return "Error: Invalid value de…
15 0 Open
Errors & debugging easy

How to Handle ValueError and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Errors & debugging easy

How to Handle ValueError in Python (try except)

Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.

try-except valueerror error-handling
Python
def divide_numbers(a, b):
    """Divide two numbers and handle ValueError safely."""
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero!"
    except TypeError:
        return "Error: Both inputs must be numbers!"


def parse…
13 0 Open
Errors & debugging easy

How to Handle ValueError with try-except in Python

Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.

error-handling try-except valueerror
Python
def get_number(prompt="Enter a number: "):
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            print("That's not a valid number. Please try again.")


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    ex…
12 0 Open
Errors & debugging easy

How to Inspect Local Variables in an except Block in Python

Capture and print local variables at the moment an exception occurs using locals() inside an except block.

debugging exception-handling locals
Python
def risky_operation(value):
    try:
        result = 10 / value
        return result
    except ZeroDivisionError as e:
        local_vars = dict(locals())
        print(f"Error: {e}")
        print("Local variables at exception:")
        for key, val in local_vars.items():
            print(f"  {key} = {val}")
   …
13 0 Open
Errors & debugging medium

How to Log Errors with Structured Fields in Python

Logs error details as structured dictionary fields using Python's logging module with extra parameters.

logging errors structured
Python
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 …
14 0 Open
Errors & debugging easy

How to Log Exceptions with traceback.format_exc in Python

Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.

traceback logging exception
Python
import traceback
import logging

def risky_operation(value):
    return 10 / value

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def main():
    try:
        result = risky_operation(0)
        print(f"Result: {result}")
    except ZeroDivisionError:
        error_msg =…
14 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.