Reference library

Errors & debugging

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

5 matches
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}")
15 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 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.

pdb debugging exceptions
Python
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…
13 0 Open
Errors & debugging medium

How to attach a request ID to exception messages in Python

This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.

contextvars exception-handling logging
Python
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="unknown")

def add_request_id(exc: Exception) -> Exception:
    exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
    return exc

d…
12 0 Open
Errors & debugging medium

How to parse a traceback to get the last frame in Python

Extracts the innermost frame's file, line, and function name from a Python traceback object.

traceback exceptions debugging
Python
import sys
import traceback


def parse_traceback_last_frame(exc_info):
    """Return the file, line, and function of the last (innermost) frame."""
    _, _, tb = exc_info
    last_tb = tb
    while last_tb.tb_next is not None:
        last_tb = last_tb.tb_next
    filename = last_tb.tb_frame.f_code.co_filename
    l…
13 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.