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):
…
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 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 Measure Python Stack Depth with inspect.stack()
Measure the current call stack depth in Python using the inspect module to understand recursion depth and debug execution context.
import inspect
def stack_depth():
return len(inspect.stack())
def recursive_function(n):
if n == 0:
print(f"Base case reached. Stack depth: {stack_depth()}")
return
recursive_function(n - 1)
if __name__ == "__main__":
print(f"Initial stack depth: {stack_depth()}")
recursive_funct…
How to Record Last N Errors with a Ring Buffer in Python
Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.
import collections
class ErrorRecorder:
def __init__(self, size):
self.buffer = collections.deque(maxlen=size)
def record_error(self, message):
self.buffer.append(message)
def get_errors(self):
return list(self.buffer)
if __name__ == "__main__":
recorder = ErrorRecorder(3)
…
How to Use a Fallback Path with FileNotFoundError in Python
Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.
import pathlib
def read_config(path):
primary = pathlib.Path(path)
fallback = pathlib.Path("config_backup.json")
try:
with primary.open("r") as f:
return f.read()
except FileNotFoundError:
try:
with fallback.open("r") as f:
return f.read()
…
How to Use pdb.post_mortem in Python
Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.
import pdb
import sys
def divide(a, b):
return a / b
def main():
try:
result = divide(10, 0)
print(f"Result: {result}")
except Exception:
# Enter post-mortem debugging when an uncaught exception occurs
pdb.post_mortem(sys.exc_info()[2])
if __name__ == "__main__":
main…
How to Use the breakpoint() Function for Interactive Debugging in Python
Insert a breakpoint() call into your code to drop into an interactive debugger session where you can inspect variables and step through execution.
def calculate_total(prices, discount=0):
"""Calculates total price with optional discount."""
subtotal = sum(prices)
breakpoint() # Interactive debugging session starts here
final_total = subtotal * (1 - discount)
return final_total
if __name__ == "__main__":
items = [25.50, 13.25, 9.99, 5.7…
How to Use try except else finally in Python
Demonstrates the correct order of try/except/else/finally blocks in Python with a safe division function.
def safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Both arguments must be numbers!")
else:
print(f"Division successful: {numerator} / {denominator…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
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")
…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
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.