Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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 Print an Exception Chain in Python for Debugging
A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.
import sys
import traceback
def pretty_exception_chain(exc):
"""Print the full exception chain with cause/context details."""
chain = []
current = exc
seen = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
chain.append(current)
curren…
How to Re-raise Exceptions with 'raise from' in Python
Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.
def divide_with_chain(a, b):
try:
result = a / b
return result
except ZeroDivisionError as original_error:
# Re-raise with explicit chaining context
raise ValueError("Cannot divide by zero") from original_error
def explain_chain():
try:
divide_with_chain(10, 0)
…
How to Simulate Timeout with Custom TimeoutError in Python
Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TimeoutError(Exception):
"""Raised when an operation exceeds its time limit."""
def __init__(self, message: str = "Operation timed out"):
self.message = message
super().__init__(self.message)
def run_with_timeout(func…
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.
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…
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.