Cyber Services / All lessons / Python Programming / Exception Handling

Exception Handling

Module 16 of 31 · 3 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Robust and Reliable Code

Why Exception Handling?

Programs encounter errors: invalid input, missing files, network failures, or logic bugs. Without handling, these cause **crashes**. Python’s exception handling lets you **gracefully manage errors**, log issues, and keep your program running.

  • Prevents abrupt termination
  • Improves user experience (e.g., “Invalid email” vs. crash)
  • Enables recovery (retry, fallback, cleanup)
  • Makes debugging easier with structured error info

The try...except Statement

The core of Python error handling. Wrap risky code in try, and define responses in except.

1. Basic Exception Handling
try:
    number = int(input("Enter a number: "))
    print("You entered:", number)
except ValueError:
    print("❌ That's not a valid integer!")
2. Handle Multiple Exception Types
try:
    x = int(input("Numerator: "))
    y = int(input("Denominator: "))
    result = x / y
    print("Result:", result)
except ValueError:
    print("❌ Please enter numbers only.")
except ZeroDivisionError:
    print("❌ Cannot divide by zero!")
3. Catch All Exceptions (Use Sparingly)
try:
    risky_operation()
except Exception as e:
    print(f"Unexpected error: {e}")
    # Log e for debugging

Full Exception Handling Structure

A try block can be followed by **multiple optional clauses**:

  • except: Handle specific errors
  • else: Run if **no exception** occurred
  • finally: **Always run**—for cleanup (e.g., close files)
4. Using else and finally
try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("❌ File not found.")
else:
    print("✅ File read successfully!")
    print(content)
finally:
    try:
        file.close()
        print("🔒 File closed.")
    except:
        pass  # file was never opened

Common Built-in Exceptions

Exception When It Occurs
ValueError Function gets right type but invalid value (e.g., int("abc"))
TypeError Operation on unsupported type (e.g., "5" + 3)
IndexError List/tuple index out of range
KeyError Dictionary key not found
FileNotFoundError File or directory doesn’t exist
ZeroDivisionError Division or modulo by zero
AttributeError Object has no such attribute/method
5. Handling KeyError in Dictionaries
user = {"name": "Ali", "age": 25}
try:
    email = user["email"]
except KeyError:
    email = "Not provided"
    print("📧 Email missing – using default.")
6. Handling IndexError
items = ["apple", "banana"]
try:
    third = items[2]
except IndexError:
    print("⚠️ Only", len(items), "items available.")

Raising Exceptions

You can **trigger exceptions manually** to enforce rules or signal errors.

7. Raise with raise
def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient funds!")
    return balance - amount

try:
    new_bal = withdraw(100, 150)
except ValueError as e:
    print("💸", e)
8. Re-raise an Exception
try:
    process_data()
except ValueError as e:
    print("Logging error:", e)
    raise  # re-raises the same exception

Custom Exceptions

Create your own exception types for domain-specific errors.

9. Define and Use Custom Exception
class InvalidAgeError(Exception):
    """Raised when age is not between 0 and 150"""
    pass

def set_age(age):
    if age < 0 or age > 150:
        raise InvalidAgeError(f"Age {age} is invalid!")
    return age

try:
    set_age(-5)
except InvalidAgeError as e:
    print("👴", e)

Practical & Real-World Patterns

10. Input Validation Loop
while True:
    try:
        age = int(input("Enter your age: "))
        if age < 0:
            raise ValueError("Age cannot be negative")
        break
    except ValueError as e:
        print("❌ Invalid input:", e)

print(f"Your age is {age}")
11. Safe File Reading with Context Manager
# Best practice: use 'with' (auto-closes file)
try:
    with open("config.txt") as f:
        data = f.read()
    print("Config loaded.")
except FileNotFoundError:
    print("⚠️ Using default settings.")
12. Chaining Exceptions (Python 3+)
try:
    process_data()
except ValueError as e:
    raise RuntimeError("Data processing failed!") from e
# Preserves original cause in traceback
13. Ignore Specific Exceptions
import os

try:
    os.remove("temp.log")
except FileNotFoundError:
    pass  # OK if file doesn't exist
14. Logging Exceptions (Production Code)
import logging

logging.basicConfig(level=logging.ERROR)

try:
    risky_api_call()
except ConnectionError as e:
    logging.error("API connection failed", exc_info=True)
    # exc_info=True includes full traceback

Best Practices

  • ✅ **Catch specific exceptions**—avoid bare except:.
  • ✅ **Use else** for code that should only run if no exception occurred.
  • ✅ **Use finally** or with for resource cleanup (files, network connections).
  • ✅ **Log exceptions** in production—don’t just print.
  • ⚠️ **Don’t ignore exceptions silently** unless intentional (e.g., file cleanup).
  • ✅ **Raise meaningful exceptions** with clear messages.

Key Takeaways

  • Exception handling = **anticipating and managing errors gracefully**.
  • Structure: try → except → (else) → (finally).
  • Always prefer **specific exception types** over generic ones.
  • Use with for files—it handles exceptions and cleanup automatically.
  • Well-handled exceptions make your programs **robust, user-friendly, and professional**.
Modules (31) ← Python Programming