Reference library

Errors & debugging

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

15 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 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 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 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.

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

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.

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

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.

ring-buffer deque error-handling
Python
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)
 …
13 0 Open
Errors & debugging easy

How to Return Success or Error as a Tuple in Python (Result Type Pattern)

Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.

result type error handling tuple unpacking
Python
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
    """Return (True, result) on success, (False, error_message) on failure."""
    if divisor == 0:
        return False, "Error: Division by zero"
    return True, dividend / divisor


if __name__ == "__main__":
    # Success case
    success, r…
11 0 Open
Errors & debugging easy

How to Serialize an Exception to a JSON-Safe Dict in Python

Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.

exceptions json logging
Python
import json
import traceback
from typing import Any


def exception_to_dict(exc: Exception) -> dict[str, Any]:
    """Convert an exception into a JSON-safe dictionary."""
    return {
        "type": type(exc).__name__,
        "message": str(exc),
        "traceback": traceback.format_exc().strip().split("\n")[-3:],
…
15 0 Open
Errors & debugging easy

How to Test Exceptions in Python with pytest.raises

Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.

pytest testing exceptions
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)


def test_divide_by_zero_raises_exact_match():
    with py…
15 0 Open
Errors & debugging easy

How to Validate Input and Raise TypeError in Python

Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.

type checking validation typeerror
Python
def validate_number(value):
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected a number, got {type(value).__name__}")
    return value * 2

if __name__ == "__main__":
    try:
        print(validate_number(5))
        print(validate_number("hello"))
    except TypeError as e:
        print(…
13 0 Open
Errors & debugging easy

How to Validate JSON in Python and Catch JSONDecodeError

A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.

json validation jsondecodeerror
Python
import json

def validate_json(json_string):
    """Try to parse JSON, return (is_valid, data_or_error)."""
    try:
        data = json.loads(json_string)
        return True, data
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

if __name__ == "__main__":
    test_inputs = [
        …
11 0 Open
Errors & debugging easy

How to catch ValueError in Python and print a friendly message

This code defines a function that safely converts text to an integer, catches ValueError, and prints a friendly message instead of crashing.

exception handling valueerror try except
Python
def parse_number(text):
    try:
        return int(text)
    except ValueError:
        print("Oops! That's not a valid number.")
        return None

if __name__ == "__main__":
    result = parse_number("abc")
    if result is None:
        print("Parsing failed.")
    else:
        print(f"Parsed value: {result}")
12 0 Open
Errors & debugging easy

How to handle ZeroDivisionError in Python

Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.

zero-division exception-handling try-except
Python
def safe_divide(a, b):
    """Return a/b if possible, else None when dividing by zero."""
    try:
        return a / b
    except ZeroDivisionError:
        return None


def safe_divide_with_message(a, b):
    """Return a how-to message on divide-by-zero error."""
    try:
        return a / b
    except ZeroDivisio…
13 0 Open
Errors & debugging easy

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.

logging stderr debugging
Python
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.…
12 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.