Reference library

Errors & debugging

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

8 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

How to Handle ValueError with try-except in Python

Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.

error-handling try-except valueerror
Python
def get_number(prompt="Enter a number: "):
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            print("That's not a valid number. Please try again.")


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    ex…
12 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

How to Validate JSON in Python and Catch JSONDecodeError

A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.

json validation jsondecodeerror
Python
import json

def validate_json(json_string):
    """Try to parse JSON, return (is_valid, data_or_error)."""
    try:
        data = json.loads(json_string)
        return True, data
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

if __name__ == "__main__":
    test_inputs = [
        …
11 0 Open
Errors & debugging easy

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.

validation regex errors
Python
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")

    #…
14 0 Open
Errors & debugging easy

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.

exception handling valueerror try except
Python
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}")
12 0 Open
Errors & debugging easy

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.

none error-handling validation
Python
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__ == "__…
15 0 Open
Errors & debugging easy

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.

exceptions domain-errors error-handling
Python
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…
14 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.