Reference library

Errors & debugging

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

5 matches
Errors & debugging easy

Catch ValueError and print friendly message in Python

Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.

error handling try except valueerror
Python
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")
13 0 Open
Errors & debugging easy

Handle ValueError and ZeroDivisionError in Python with try except

Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.

try-except valueerror zerodivisionerror
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ValueError as e:
        print(f"ValueError caught: {e}")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    return result

# Test cases
print(safe_divide…
12 0 Open
Errors & debugging easy

How to Return Success or Error as a Tuple in Python (Result Type Pattern)

Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.

result type error handling tuple unpacking
Python
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
    """Return (True, result) on success, (False, error_message) on failure."""
    if divisor == 0:
        return False, "Error: Division by zero"
    return True, dividend / divisor


if __name__ == "__main__":
    # Success case
    success, r…
10 0 Open
Errors & debugging easy

How to Validate Input and Raise TypeError in Python

Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.

type checking validation typeerror
Python
def validate_number(value):
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected a number, got {type(value).__name__}")
    return value * 2

if __name__ == "__main__":
    try:
        print(validate_number(5))
        print(validate_number("hello"))
    except TypeError as e:
        print(…
13 0 Open
Errors & debugging easy

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.

exceptions http-status error-handling
Python
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…
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.