Module 25: Handling the Unexpected

Building robust Python code that doesn't crash easily.

🛡️ Why Bother With Errors?

Real-world programs encounter unexpected situations: bad user input, network problems, missing files...

Without error handling, your program might just crash! Exception handling makes your code robust.

Without Handling

An unexpected error occurs... Program stops abruptly. User sees a scary error message (or nothing). Data might be lost.

With Handling (try...except)

An unexpected error occurs... The program catches it, handles it gracefully (e.g., shows a user-friendly message, retries), and continues running or exits cleanly.

🧱 The `try...except` Block

Python uses `try` and `except` to manage potential errors.

1. Code inside the `try` block is executed first.
2. If an error occurs in the `try` block, Python stops and jumps to the `except` block.
3. If no error occurs, the `except` block is skipped.

try: # Attempt this code
  age_str = input("Enter your age: ")
  age = int(age_str) # This might fail if input isn't a number!
  print(f"Next year you'll be {age + 1}")
except: # If ANY error happens in the try block...
  print("Oops! Please enter a valid number for age.")

Execution Flow:

Try Block Except Block Continue No Error Error!

🎯 Catching Specific Errors

It's better to catch specific types of errors instead of using a generic `except`. This lets you handle different problems differently.

Handling Bad Input (`ValueError`)

try:
  num_str = input("Enter a number: ")
  number = int(num_str)
  print(f"Number doubled: {number * 2}")
except ValueError: # Catch ONLY this specific error
  print("Invalid input. Please enter digits only.")

Handling Division by Zero (`ZeroDivisionError`)

try:
  numerator = 10
  denominator = int(input("Divide 10 by: "))
  result = numerator / denominator
  print(f"Result: {result}")
except ValueError:
  print("Please enter a number.")
except ZeroDivisionError: # Catch a different error
  print("Cannot divide by zero!")

You can have multiple `except` blocks to handle different potential errors from the `try` block. Common errors include `TypeError`, `FileNotFoundError`, `IndexError`, etc.

🧠 Quick Check!

Module 25 Theory Complete!

Excellent! You've learned how to make your Python code more robust using exception handling.
Ready to practice catching errors? Head to the Practice Zone or try the Advanced Practice.