Reference library

Errors & debugging

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

4 matches
Errors & debugging easy

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.

debugging context-manager performance
Python
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…
15 0 Open
Errors & debugging easy

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.

inspect recursion stack
Python
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…
16 0 Open
Errors & debugging easy

How to Raise a Custom Exception with Extra Context in Python

Define a custom exception that carries extra context fields and raise it to provide richer error information.

exceptions custom-exception error-handling
Python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")


def withdraw(balance, amount):
    if amount > balance:
        raise Insuffici…
13 0 Open
Errors & debugging easy

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.

context-manager exception-handling with-statement
Python
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…
11 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.