Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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.
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…
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.
try:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
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.
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):
…
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.
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…
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.
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…
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.
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}")
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.
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…
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.
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…
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.
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…
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.
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__ == "_…
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:
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.")
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.
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…
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.
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…
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.
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…
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.
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…
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.
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], "<…
How to Dump a Debugging Repr for Unknown Types in Python
Build a fallback repr that shows dataclass fields or object attributes for any value, handy when debugging unknown types.
import dataclasses
from typing import Any
@dataclasses.dataclass
class Sample:
name: str
values: list[int]
def dump_repr(obj: Any) -> str:
"""Return a concise but complete repr for debugging unknown types."""
if dataclasses.is_dataclass(obj):
fields = ", ".join(
f"{field.name}={…
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.
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…
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.
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…
How to Handle ValueError When Converting Strings to Integers in Python
Convert text to an integer with a try-except block that catches ValueError and prints beginner-friendly error messages.
def parse_number(text):
"""Convert text to an integer, showing beginner-friendly error handling."""
try:
number = int(text)
print(f"Successfully parsed: {number}")
return number
except ValueError as e:
print(f"Error: '{text}' is not a valid number.")
print(f"Debuggin…
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.
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…
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.
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…
How to Handle ValueError with try except in Python
Shows a beginner-friendly try/except pattern that catches ValueError when converting text to an integer, prints a helpful message, and returns None instead of crashing.
def parse_number(text):
try:
return int(text)
except ValueError:
print(f"ValueError: '{text}' is not a valid integer.")
return None
if __name__ == "__main__":
user_input = "abc"
result = parse_number(user_input)
print(f"Parsing '{user_input}' returned: {result}")
vali…
How to Handle ValueError with try-except in Python
Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.
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…
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.