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 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.
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…
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.
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…
How to Validate an Email Address and Raise ValueError in Python
This code defines a validate_email function that checks an email address against a regex pattern and several rules, raising ValueError with a specific reason when invalid.
import re
def validate_email(email: str) -> str:
"""Validate an email address and return it if valid, otherwise raise ValueError."""
if not isinstance(email, str):
raise ValueError("Email must be a string")
if len(email) > 254:
raise ValueError("Email length exceeds 254 characters")
#…
How to check for None and raise helpful errors in Python
A defensive function that explicitly validates data, keys, and values — raising descriptive ValueError and KeyError exceptions before returning a result.
def get_value(data, key):
if data is None:
raise ValueError("data cannot be None")
if key not in data:
raise KeyError(f"key '{key}' not found in data")
result = data[key]
if result is None:
raise ValueError(f"value for key '{key}' is None")
return result
if __name__ == "__…
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.