10  Exception Handling

10.1 Introduction

Exception handling is a crucial concept in Python that allows you to handle errors gracefully instead of letting your program crash. In this tutorial, you’ll learn:

  • What exceptions are and why they matter
  • How to catch and handle exceptions
  • The difference between try-except, try-except-else, and try-except-finally
  • Best practices for robust error handling

10.2 Understanding Exceptions

10.3 What is an Exception?

An exception is an error that occurs during program execution. When Python encounters an error, it “raises” an exception and stops the program unless you handle it.

Common Exception Types

# Let's see some common exceptions (we'll catch them later!)

# Example 1: ZeroDivisionError
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
    print(f"Type: {type(e).__name__}")
Error: division by zero
Type: ZeroDivisionError
# Example 2: ValueError
try:
    number = int("hello")
except ValueError as e:
    print(f"Error: {e}")
    print(f"Type: {type(e).__name__}")
Error: invalid literal for int() with base 10: 'hello'
Type: ValueError
# Example 3: FileNotFoundError
try:
    with open("nonexistent_file.txt", "r") as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"Error: {e}")
    print(f"Type: {type(e).__name__}")
Error: [Errno 2] No such file or directory: 'nonexistent_file.txt'
Type: FileNotFoundError
# Example 4: KeyError (dictionary)
try:
    my_dict = {"name": "Alice", "age": 25}
    print(my_dict["address"])
except KeyError as e:
    print(f"Error: Key {e} not found")
    print(f"Type: {type(e).__name__}")
Error: Key 'address' not found
Type: KeyError
# Example 5: IndexError (list)
try:
    my_list = [1, 2, 3]
    print(my_list[10])
except IndexError as e:
    print(f"Error: {e}")
    print(f"Type: {type(e).__name__}")
Error: list index out of range
Type: IndexError

10.4 Why Handle Exceptions?

Without exception handling:

# This would crash the program
age = int(input("Enter your age: "))  # User enters "twenty"
# Program crashes with ValueError!

With exception handling:

# Safe version
try:
    age_input = "twenty"  # Simulating user input
    age = int(age_input)
    print(f"Your age is {age}")
except ValueError:
    print("Please enter a valid number!")
    age = None
Please enter a valid number!

10.5 Basic Try-Except

The try-except block is the foundation of exception handling.

10.6 Basic Syntax

try:
    # Code that might raise an exception
    risky_operation()
except ExceptionType:
    # Code to handle the exception
    handle_error()

10.7 Simple Example

# Division calculator
def divide(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        return None

print(divide(10, 2))   # Works fine
print(divide(10, 0))   # Handles error gracefully
5.0
Error: Cannot divide by zero!
None

10.8 Catching the Exception Object

# Access error details
try:
    number = int("not a number")
except ValueError as e:
    print(f"Caught an error: {e}")
    print(f"Error type: {type(e).__name__}")
Caught an error: invalid literal for int() with base 10: 'not a number'
Error type: ValueError

10.9 Real-World Example: Reading Files

def read_file_safely(filename):
    try:
        with open(filename, 'r') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")
        return None

# Test with existing file
content = read_file_safely('data/sample.txt')
if content:
    print(f"File read successfully! ({len(content)} characters)")

# Test with non-existent file
content = read_file_safely('data/missing.txt')
File read successfully! (127 characters)
Error: The file 'data/missing.txt' was not found.

10.10 Multiple Exception Handlers

You can catch different types of exceptions separately.

10.11 Multiple Except Blocks

def process_number(value):
    try:
        # Convert to integer
        num = int(value)
        # Divide 100 by the number
        result = 100 / num
        return result
    except ValueError:
        print(f"Error: '{value}' is not a valid number")
        return None
    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None

# Test different scenarios
print(process_number("20"))      # Success: 5.0
print(process_number("hello"))   # ValueError
print(process_number("0"))       # ZeroDivisionError
5.0
Error: 'hello' is not a valid number
None
Error: Cannot divide by zero
None

10.12 Catching Multiple Exceptions Together

def safe_division(a, b):
    try:
        result = int(a) / int(b)
        return result
    except (ValueError, ZeroDivisionError) as e:
        print(f"Error occurred: {type(e).__name__} - {e}")
        return None

print(safe_division("10", "2"))    # Success
print(safe_division("10", "abc"))  # ValueError
print(safe_division("10", "0"))    # ZeroDivisionError
5.0
Error occurred: ValueError - invalid literal for int() with base 10: 'abc'
None
Error occurred: ZeroDivisionError - division by zero
None

10.13 Catch-All Exception Handler

def risky_operation(value):
    try:
        # Multiple things that could go wrong
        num = int(value)
        result = 100 / num
        my_list = [1, 2, 3]
        return my_list[num]
    except ValueError:
        print("Invalid number format")
    except ZeroDivisionError:
        print("Cannot divide by zero")
    except IndexError:
        print("Index out of range")
    except Exception as e:
        # Catches any other exception
        print(f"Unexpected error: {type(e).__name__} - {e}")

risky_operation("2")      # Success
risky_operation("abc")    # ValueError
risky_operation("0")      # ZeroDivisionError
risky_operation("10")     # IndexError
Invalid number format
Cannot divide by zero
Index out of range

10.14 Try-Except-Else

The else block runs only if no exception occurred in the try block.

10.15 Syntax

try:
    # Code that might raise an exception
    risky_code()
except ExceptionType:
    # Handle the exception
    handle_error()
else:
    # Runs only if no exception occurred
    success_code()

10.16 Basic Example

def divide_with_else(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Division by zero!")
    else:
        print(f"Success! {a} / {b} = {result}")
        return result

divide_with_else(10, 2)
divide_with_else(10, 0)
Success! 10 / 2 = 5.0
Error: Division by zero!

10.17 File Processing Example

def process_file(filename):
    try:
        with open(filename, 'r') as file:
            content = file.read()
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return None
    else:
        # Only runs if file was opened successfully
        print(f"File read successfully!")
        lines = content.split('\n')
        print(f"Number of lines: {len(lines)}")
        return lines

# Test both scenarios
print("\nTest 1 - Existing file:")
result = process_file('data/sample.txt')

print("\nTest 2 - Missing file:")
result = process_file('data/nonexistent.txt')

Test 1 - Existing file:
File read successfully!
Number of lines: 6

Test 2 - Missing file:
Error: File 'data/nonexistent.txt' not found

10.18 Why Use Else?

The else block makes code clearer by separating: - try: Code that might fail - except: Error handling - else: Success handling

import json

def load_config(filename):
    try:
        with open(filename, 'r') as file:
            config = json.load(file)
    except FileNotFoundError:
        print("Config file not found, using defaults")
        config = {"default": True}
    except json.JSONDecodeError:
        print("Invalid JSON format, using defaults")
        config = {"default": True}
    else:
        print("Configuration loaded successfully!")
        print(f"Config keys: {list(config.keys())}")

    return config

# Test with valid JSON
result = load_config('data/inventory.json')
Configuration loaded successfully!
Config keys: ['products', 'warehouse', 'last_updated']

10.19 Try-Except-Finally

The finally block always runs, whether an exception occurred or not. It’s perfect for cleanup operations.

10.20 Syntax

try:
    # Code that might raise an exception
    risky_code()
except ExceptionType:
    # Handle the exception
    handle_error()
finally:
    # Always runs (cleanup code)
    cleanup()

10.21 Basic Example

def demonstrate_finally(value):
    try:
        result = 10 / value
        print(f"Result: {result}")
    except ZeroDivisionError:
        print("Error: Division by zero")
    finally:
        print("This always runs, no matter what!")

demonstrate_finally(2)   # Success
print()
demonstrate_finally(0)   # Error
Result: 5.0
This always runs, no matter what!

Error: Division by zero
This always runs, no matter what!

10.22 File Handling Example

def read_file_with_finally(filename):
    file = None
    try:
        print(f"Opening {filename}...")
        file = open(filename, 'r')
        content = file.read()
        print(f"Read {len(content)} characters")
        return content
    except FileNotFoundError:
        print(f"Error: File not found")
        return None
    finally:
        # Ensure file is closed even if error occurs
        if file:
            file.close()
            print("File closed")
        else:
            print("No file to close")

print("Test 1:")
read_file_with_finally('data/sample.txt')
print("\nTest 2:")
read_file_with_finally('data/missing.txt')
Test 1:
Opening data/sample.txt...
Read 127 characters
File closed

Test 2:
Opening data/missing.txt...
Error: File not found
No file to close

Note: With with statement, you don’t need finally for files:

# The 'with' statement handles cleanup automatically
try:
    with open('data/sample.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("File not found")
# File is automatically closed here

10.23 All Together: Try-Except-Else-Finally

def complete_example(filename):
    print(f"\n--- Processing {filename} ---")
    try:
        with open(filename, 'r') as file:
            content = file.read()
            lines = content.split('\n')
    except FileNotFoundError:
        print("ERROR: File not found")
        lines = []
    else:
        print(f"SUCCESS: Read {len(lines)} lines")
    finally:
        print("CLEANUP: Processing complete")

    return lines

complete_example('data/sample.txt')
complete_example('data/missing.txt')

--- Processing data/sample.txt ---
SUCCESS: Read 6 lines
CLEANUP: Processing complete

--- Processing data/missing.txt ---
ERROR: File not found
CLEANUP: Processing complete
[]

10.24 Practical Examples

10.25 Processing Numeric Data

Let’s process a file with mixed valid and invalid numbers:

# Read and process numbers from file
def process_numbers(filename):
    valid_numbers = []
    invalid_entries = []

    try:
        with open(filename, 'r') as file:
            for line_num, line in enumerate(file, 1):
                line = line.strip()
                if not line:  # Skip empty lines
                    continue

                try:
                    number = float(line)
                    valid_numbers.append(number)
                except ValueError:
                    invalid_entries.append((line_num, line))
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return None, None
    else:
        print(f"Processed {len(valid_numbers)} valid numbers")
        print(f"Found {len(invalid_entries)} invalid entries")

    return valid_numbers, invalid_entries

# Process the numbers file
numbers, errors = process_numbers('data/numbers.txt')

if numbers is not None:
    print(f"\nValid numbers: {numbers}")
    print(f"Invalid entries: {errors}")
    print(f"Sum of valid numbers: {sum(numbers)}")
Error: File 'data/numbers.txt' not found

10.26 Configuration Parser

def parse_config(filename):
    config = {}
    errors = []

    try:
        with open(filename, 'r') as file:
            for line_num, line in enumerate(file, 1):
                line = line.strip()
                if not line or line.startswith('#'):
                    continue

                try:
                    key, value = line.split('=')
                    key = key.strip()
                    value = value.strip()

                    # Try to convert to int
                    try:
                        config[key] = int(value)
                    except ValueError:
                        # Keep as string if not a number
                        config[key] = value

                except ValueError:
                    errors.append(f"Line {line_num}: Invalid format")

    except FileNotFoundError:
        print(f"Error: Config file not found")
        return None
    else:
        if errors:
            print("Warnings during parsing:")
            for error in errors:
                print(f"  - {error}")

    return config

config = parse_config('data/config.txt')
print("\nParsed configuration:")
for key, value in config.items():
    print(f"  {key}: {value} (type: {type(value).__name__})")

Parsed configuration:
  debug: 1 (type: int)
  max_connections: 100 (type: int)
  timeout: 30 (type: int)
  server_name: localhost (type: str)
  port: 8080 (type: int)

10.27 User Input Validation

def get_valid_age(age_str, max_attempts=3):
    """
    Validate age input with retry logic
    """
    for attempt in range(max_attempts):
        try:
            age = int(age_str)

            if age < 0:
                raise ValueError("Age cannot be negative")
            if age > 150:
                raise ValueError("Age seems unrealistic")

        except ValueError as e:
            print(f"Attempt {attempt + 1}: Invalid input - {e}")
            if attempt < max_attempts - 1:
                # In real scenario, would ask for new input
                age_str = "25"  # Simulated correction
                print(f"  (Retrying with: {age_str})")
            else:
                print("Max attempts reached")
                return None
        else:
            print(f"Valid age accepted: {age}")
            return age

    return None

# Test various scenarios
print("Test 1 - Invalid then valid:")
get_valid_age("abc")

print("\nTest 2 - Negative age:")
get_valid_age("-5")

print("\nTest 3 - Valid age:")
get_valid_age("25")
Test 1 - Invalid then valid:
Attempt 1: Invalid input - invalid literal for int() with base 10: 'abc'
  (Retrying with: 25)
Valid age accepted: 25

Test 2 - Negative age:
Attempt 1: Invalid input - Age cannot be negative
  (Retrying with: 25)
Valid age accepted: 25

Test 3 - Valid age:
Valid age accepted: 25
25

10.28 Raising Exceptions

You can raise exceptions yourself to signal errors.

10.29 Basic Raise

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age must be realistic")
    return True

try:
    validate_age(25)   # OK
    print("Age 25 is valid")
    validate_age(-5)   # Raises error
except ValueError as e:
    print(f"Validation error: {e}")
Age 25 is valid
Validation error: Age cannot be negative

10.30 Re-raising Exceptions

def process_data(value):
    try:
        result = int(value) / 10
    except ValueError as e:
        print(f"Logging error: {e}")
        raise  # Re-raise the same exception
    return result

try:
    process_data("invalid")
except ValueError:
    print("Caught re-raised exception in outer handler")
Logging error: invalid literal for int() with base 10: 'invalid'
Caught re-raised exception in outer handler

10.31 Custom Exceptions

# Define custom exception
class InsufficientFundsError(Exception):
    """Raised when account has insufficient funds"""
    pass

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(
                f"Cannot withdraw ${amount}. Balance: ${self.balance}"
            )
        self.balance -= amount
        return self.balance

# Use custom exception
account = BankAccount(100)

try:
    account.withdraw(50)
    print(f"Withdrew $50. Balance: ${account.balance}")
    account.withdraw(100)  # This will fail
except InsufficientFundsError as e:
    print(f"Transaction failed: {e}")
Withdrew $50. Balance: $50
Transaction failed: Cannot withdraw $100. Balance: $50

10.32 Best Practices

10.33 Be Specific with Exceptions

# GOOD - Specific exception handling
def read_json_file(filename):
    try:
        with open(filename, 'r') as file:
            data = json.load(file)
    except FileNotFoundError:
        print(f"File {filename} not found")
    except json.JSONDecodeError:
        print(f"Invalid JSON in {filename}")
    except PermissionError:
        print(f"No permission to read {filename}")
    return None

# AVOID - Too broad
def read_json_bad(filename):
    try:
        with open(filename, 'r') as file:
            data = json.load(file)
    except Exception:  # Too broad!
        print("Something went wrong")
    return None

10.34 Don’t Ignore Exceptions

# BAD - Silent failure
try:
    result = 10 / 0
except:
    pass  # Error is hidden!

# GOOD - At least log it
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error occurred: {e}")
    result = None
Error occurred: division by zero

10.35 Use Finally for Cleanup

import os

def process_file_safely(filename):
    file = None
    temp_file = "temp_processing.txt"

    try:
        file = open(filename, 'r')
        content = file.read()

        # Create temp file
        with open(temp_file, 'w') as tf:
            tf.write(content.upper())

        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
    finally:
        # Cleanup
        if file:
            file.close()
        # Remove temp file if it exists
        if os.path.exists(temp_file):
            os.remove(temp_file)
            print("Temp file cleaned up")

10.36 Provide Context in Error Messages

def divide_list_elements(numbers, divisor):
    results = []
    for i, num in enumerate(numbers):
        try:
            result = num / divisor
            results.append(result)
        except ZeroDivisionError:
            # Provide context: which element, what value
            print(f"Error at index {i}: Cannot divide {num} by zero")
            results.append(None)
        except TypeError:
            print(f"Error at index {i}: {num} is not a number")
            results.append(None)
    return results

numbers = [10, 20, "30", 40]
results = divide_list_elements(numbers, 0)
print(f"Results: {results}")
Error at index 0: Cannot divide 10 by zero
Error at index 1: Cannot divide 20 by zero
Error at index 2: 30 is not a number
Error at index 3: Cannot divide 40 by zero
Results: [None, None, None, None]

10.37 Exercises

10.38 Exercise 1: Safe Calculator

Task: Create a calculator function that: 1. Takes two numbers and an operation (+, -, *, /) 2. Handles division by zero 3. Handles invalid operations 4. Uses try-except-else

def calculator(num1, num2, operation):
    # Your code here
    pass

# Test cases
print(calculator(10, 5, '+'))   # Should return 15
print(calculator(10, 5, '/'))   # Should return 2.0
print(calculator(10, 0, '/'))   # Should handle division by zero
print(calculator(10, 5, '^'))   # Should handle invalid operation

Solution:

Click to show solution
def calculator(num1, num2, operation):
    try:
        if operation == '+':
            result = num1 + num2
        elif operation == '-':
            result = num1 - num2
        elif operation == '*':
            result = num1 * num2
        elif operation == '/':
            result = num1 / num2
        else:
            raise ValueError(f"Invalid operation: {operation}")
    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None
    except ValueError as e:
        print(f"Error: {e}")
        return None
    else:
        print(f"Success: {num1} {operation} {num2} = {result}")
        return result

# Test cases
calculator(10, 5, '+')
calculator(10, 5, '/')
calculator(10, 0, '/')
calculator(10, 5, '^')
Success: 10 + 5 = 15
Success: 10 / 5 = 2.0
Error: Cannot divide by zero
Error: Invalid operation: ^

10.39 Exercise 2: File Statistics

Task: Write a function that: 1. Reads a file with numbers (one per line) 2. Calculates sum, average, min, max 3. Handles file not found 4. Handles non-numeric values 5. Uses try-except-else-finally

def file_statistics(filename):
    # Your code here
    pass

file_statistics('data/numbers.txt')

Solution:

Click to show solution
def file_statistics(filename):
    numbers = []
    errors = 0

    try:
        with open(filename, 'r') as file:
            for line in file:
                line = line.strip()
                if not line:
                    continue
                try:
                    number = float(line)
                    numbers.append(number)
                except ValueError:
                    errors += 1
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return None
    else:
        if numbers:
            stats = {
                'count': len(numbers),
                'sum': sum(numbers),
                'average': sum(numbers) / len(numbers),
                'min': min(numbers),
                'max': max(numbers)
            }
            print(f"Successfully processed {len(numbers)} numbers")
            if errors:
                print(f"Skipped {errors} invalid entries")
            return stats
        else:
            print("No valid numbers found")
            return None
    finally:
        print("File processing complete")

stats = file_statistics('data/numbers.txt')
if stats:
    print("\nStatistics:")
    for key, value in stats.items():
        print(f"  {key}: {value}")
Error: File 'data/numbers.txt' not found
File processing complete

10.40 Exercise 3: Score Parser

Task: Create a function that: 1. Reads data/scores.txt (format: “Name:Score”) 2. Parses each line into a dictionary 3. Handles missing scores (empty after colon) 4. Handles invalid score values 5. Returns valid scores and lists errors

def parse_scores(filename):
    # Your code here
    pass

scores, errors = parse_scores('data/scores.txt')

Solution:

Click to show solution
def parse_scores(filename):
    scores = {}
    errors = []

    try:
        with open(filename, 'r') as file:
            for line_num, line in enumerate(file, 1):
                line = line.strip()
                if not line:
                    continue

                try:
                    # Split by colon
                    name, score_str = line.split(':')
                    name = name.strip()
                    score_str = score_str.strip()

                    # Handle empty score
                    if not score_str:
                        raise ValueError("Missing score")

                    # Convert to int
                    score = int(score_str)

                    # Validate score range
                    if score < 0 or score > 100:
                        raise ValueError("Score out of range (0-100)")

                    scores[name] = score

                except ValueError as e:
                    error_msg = f"Line {line_num} ({line}): {e}"
                    errors.append(error_msg)

    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return None, None
    else:
        print(f"Parsed {len(scores)} valid scores")
        if errors:
            print(f"Found {len(errors)} errors")

    return scores, errors

scores, errors = parse_scores('data/scores.txt')

if scores is not None:
    print("\nValid Scores:")
    for name, score in scores.items():
        print(f"  {name}: {score}")

    if errors:
        print("\nErrors:")
        for error in errors:
            print(f"  - {error}")
Error: File 'data/scores.txt' not found

10.41 Exercise 4: Robust JSON Loader

Task: Create a function that: 1. Tries to load a JSON file 2. If file not found, creates it with default data 3. If JSON is invalid, backs up the corrupted file and creates new one 4. Returns the loaded or created data 5. Uses try-except-else-finally

def load_or_create_json(filename, default_data=None):
    # Your code here
    pass

data = load_or_create_json('exercises/settings.json', {'theme': 'light', 'lang': 'en'})

Solution:

Click to show solution
import json
import os
from datetime import datetime

def load_or_create_json(filename, default_data=None):
    if default_data is None:
        default_data = {}

    data = None
    operation = None

    try:
        with open(filename, 'r') as file:
            data = json.load(file)
            operation = "loaded"
    except FileNotFoundError:
        print(f"File not found. Creating {filename} with defaults.")
        data = default_data
        operation = "created"
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {filename}: {e}")
        # Backup corrupted file
        backup_name = f"{filename}.corrupted.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        if os.path.exists(filename):
            os.rename(filename, backup_name)
            print(f"Corrupted file backed up to: {backup_name}")
        data = default_data
        operation = "recreated"
    else:
        print(f"Successfully loaded {filename}")
    finally:
        # Save data if it was created or recreated
        if operation in ["created", "recreated"]:
            try:
                with open(filename, 'w') as file:
                    json.dump(data, file, indent=2)
                print(f"Saved {filename}")
            except Exception as e:
                print(f"Error saving file: {e}")

    return data

# Test the function
default_settings = {'theme': 'light', 'language': 'en', 'notifications': True}
data = load_or_create_json('exercises/settings.json', default_settings)
print(f"\nData: {json.dumps(data, indent=2)}")
Successfully loaded exercises/settings.json

Data: {
  "theme": "dark",
  "language": "en",
  "notifications": true,
  "auto_save": true
}

10.42 Exercise 5: Advanced - Data Validator

Task: Create a comprehensive data validation system: 1. Define custom exceptions for different validation errors 2. Validate user data (age, email format, username length) 3. Collect all validation errors (don’t stop at first error) 4. Return valid data or raise exception with all errors

class ValidationError(Exception):
    pass

def validate_user_data(data):
    # Your code here
    pass

# Test data
test_users = [
    {"username": "alice", "age": 25, "email": "alice@example.com"},
    {"username": "ab", "age": -5, "email": "invalid-email"},
    {"username": "bob_smith", "age": 30, "email": "bob@example.com"}
]

Solution:

Click to show solution
import re

class ValidationError(Exception):
    """Custom exception for validation errors"""
    pass

class InvalidAgeError(ValidationError):
    pass

class InvalidEmailError(ValidationError):
    pass

class InvalidUsernameError(ValidationError):
    pass

def validate_user_data(data):
    """
    Validate user data dictionary.
    Raises ValidationError with all issues found.
    """
    errors = []

    # Validate username
    try:
        username = data.get('username', '')
        if len(username) < 3:
            raise InvalidUsernameError("Username must be at least 3 characters")
        if len(username) > 20:
            raise InvalidUsernameError("Username must be at most 20 characters")
        if not username.replace('_', '').isalnum():
            raise InvalidUsernameError("Username can only contain letters, numbers, and underscores")
    except InvalidUsernameError as e:
        errors.append(f"Username: {e}")

    # Validate age
    try:
        age = data.get('age')
        if age is None:
            raise InvalidAgeError("Age is required")
        if not isinstance(age, int):
            raise InvalidAgeError("Age must be an integer")
        if age < 0:
            raise InvalidAgeError("Age cannot be negative")
        if age > 150:
            raise InvalidAgeError("Age must be realistic")
    except InvalidAgeError as e:
        errors.append(f"Age: {e}")

    # Validate email
    try:
        email = data.get('email', '')
        # Simple email regex
        email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if not re.match(email_pattern, email):
            raise InvalidEmailError("Invalid email format")
    except InvalidEmailError as e:
        errors.append(f"Email: {e}")

    # If there are errors, raise exception with all of them
    if errors:
        error_message = "Validation failed:\n  - " + "\n  - ".join(errors)
        raise ValidationError(error_message)

    return True

# Test with multiple users
test_users = [
    {"username": "alice", "age": 25, "email": "alice@example.com"},
    {"username": "ab", "age": -5, "email": "invalid-email"},
    {"username": "bob_smith", "age": 30, "email": "bob@example.com"},
    {"username": "x", "age": 200, "email": "notemail"}
]

for i, user in enumerate(test_users, 1):
    print(f"\nValidating user {i}: {user['username']}")
    try:
        validate_user_data(user)
        print("  ✓ Validation passed!")
    except ValidationError as e:
        print(f"  ✗ {e}")

Validating user 1: alice
  ✓ Validation passed!

Validating user 2: ab
  ✗ Validation failed:
  - Username: Username must be at least 3 characters
  - Age: Age cannot be negative
  - Email: Invalid email format

Validating user 3: bob_smith
  ✓ Validation passed!

Validating user 4: x
  ✗ Validation failed:
  - Username: Username must be at least 3 characters
  - Age: Age must be realistic
  - Email: Invalid email format

11 10. Summary

Congratulations! You’ve learned comprehensive exception handling in Python.

11.1 Key Takeaways

  1. Exceptions are errors that occur during program execution
  2. try-except catches and handles specific exceptions
  3. try-except-else runs code only when no exception occurs
  4. try-except-finally ensures cleanup code always runs
  5. Raise your own exceptions to signal errors
  6. Custom exceptions make your code more maintainable

11.2 Exception Handling Cheat Sheet

# Basic structure
try:
    # Code that might raise exceptions
    risky_operation()
except SpecificError as e:
    # Handle specific exception
    handle_error(e)
except (Error1, Error2):
    # Handle multiple exceptions
    handle_multiple()
except Exception as e:
    # Catch-all (use sparingly)
    handle_unknown(e)
else:
    # Runs only if no exception
    success_code()
finally:
    # Always runs (cleanup)
    cleanup()

# Raising exceptions
raise ValueError("Custom message")
raise  # Re-raise current exception

# Custom exceptions
class MyCustomError(Exception):
    pass

11.3 Common Exceptions

Exception When It Occurs
ValueError Invalid value for operation
TypeError Wrong type for operation
ZeroDivisionError Division by zero
FileNotFoundError File doesn’t exist
KeyError Dictionary key not found
IndexError List index out of range
AttributeError Attribute doesn’t exist
ImportError Module can’t be imported

11.4 Best Practices Reminder

  1. Be specific with exception types
  2. Don’t silently ignore exceptions
  3. Use finally for cleanup
  4. Provide helpful error messages
  5. Don’t catch Exception unless necessary
  6. Use context managers (with) when possible

Happy coding!