Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
How to catch ValueError in Python and print a friendly message
This code defines a function that safely converts text to an integer, catches ValueError, and prints a friendly message instead of crashing.
def parse_number(text):
try:
return int(text)
except ValueError:
print("Oops! That's not a valid number.")
return None
if __name__ == "__main__":
result = parse_number("abc")
if result is None:
print("Parsing failed.")
else:
print(f"Parsed value: {result}")
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__ == "__…
How to define an exception hierarchy for domain errors in Python
Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.
class DomainError(Exception):
"""Base class for all domain errors."""
pass
class ValidationError(DomainError):
"""Raised when input data fails validation rules."""
pass
class NotFoundError(DomainError):
"""Raised when a requested entity does not exist."""
pass
class PermissionDeniedError(Dom…
How to handle ZeroDivisionError in Python
Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.
def safe_divide(a, b):
"""Return a/b if possible, else None when dividing by zero."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_divide_with_message(a, b):
"""Return a how-to message on divide-by-zero error."""
try:
return a / b
except ZeroDivisio…
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…
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.
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…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
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.
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…
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.
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")…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
Split try except ValueError handler for beginners in Python
Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.
def parse_number(text):
try:
number = int(text)
return f"Parsed successfully: {number}"
except ValueError as error:
return f"Conversion failed: {error}"
def divide_numbers(dividend, divisor):
try:
result = dividend / divisor
return f"Division result: {result}"
e…
Try Except ValueError in Python: Handle Conversion Errors
Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.
def convert_to_int(value):
try:
return int(value)
except ValueError as error:
print(f"Conversion failed: {error}")
print(f"Problem value was: {repr(value)}")
return None
def divide_numbers(numerator, denominator):
try:
result = numerator / denominator
retur…
Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
from pprint import pprint
def build_nested_structure():
"""Create a sample nested data structure for demonstration."""
return {
"project": "DataPipeline",
"config": {
"inputs": ["raw_1.json", "raw_2.json"],
"processing": {
"steps": ["clean", "transform",…
Validate try except ValueError handler for beginners — errors debugging
Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.
def divide_numbers(a, b):
"""Divide two numbers, catching division by zero and value errors."""
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Both arguments must be numbers!")
retu…
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.