Reference library

Errors & debugging

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

6 matches
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__ == "_…
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 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 Use Optional Return in Python Instead of Raising Exceptions

A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.

optional typing dict-get
Python
from typing import Optional


def find_user(users: dict, user_id: int) -> Optional[dict]:
    """
    Look up a user by ID. Returns the user dict if found,
    otherwise returns None instead of raising KeyError.
    """
    return users.get(user_id)


def main() -> None:
    users = {
        1: {"name": "Alice", "ema…
14 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

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.