Module 5 Lesson 6: Handling Exceptions (Try-Except)
·Programming

Module 5 Lesson 6: Handling Exceptions (Try-Except)

Stop your code from crashing. Learn how to catch errors gracefully and provide helpful feedback instead of the 'Red Screen of Death'.

Module 5 Lesson 6: Handling Exceptions (Try-Except)

Errors are a part of life. A user might try to open a file that doesn't exist, or they might try to divide a number by zero. Usually, this causes your program to crash instantly. In this lesson, we’ll learn how to "catch" these errors so your program can stay running.

Lesson Overview

In this lesson, we will cover:

  • What is an Exception?: Bugs vs. Exceptions.
  • The try Block: Testing code that might fail.
  • The except Block: The safety net.
  • Basic Example: Handling the "File Not Found" error.

1. What is an Exception?

A Syntax Error is a mistake in your grammar (like a missing colon), and your code won't even start.

An Exception is an error that happens while the code is running. The code is written correctly, but something outside your control goes wrong (like a lost internet connection or a missing file).


2. Using try and except

Think of try as saying: "Try to run this code, but if it breaks, don't crash the whole computer. Jump to the except block instead."

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except:
    print("Oops! Something went wrong. Did you enter a zero or a word?")

print("The program is still running!")

3. Handling Files Safely

One of the most common exceptions is trying to read a file that isn't there.

try:
    with open("secret_codes.txt", "r") as file:
        print(file.read())
except:
    print("Warning: The file 'secret_codes.txt' could not be found.")

4. Why Catch Exceptions?

  1. User Experience: A friendly "File not found" message is much better than 10 lines of scary red error text.
  2. Stability: In a professional app (like a web server), you don't want the whole site to go down just because one user uploaded the wrong file.
  3. Cleanup: You can use exceptions to ensure that even if a crash happens, you still save the user's progress or close open database connections.

Practice Exercise: The Division Guard

  1. Write a script that asks the user for two numbers.
  2. Try to divide the first number by the second.
  3. Use a try-except block to catch any errors.
  4. If an error happens, print: "Error: Calculation could not be completed."
  5. If it works, print the result.

Quick Knowledge Check

  1. What is the difference between a Syntax Error and an Exception?
  2. What does the try block do?
  3. What happens to the code inside the try block once an error occurs?
  4. Does the code after the try-except block run if an exception is caught?

Key Takeaways

  • Exceptions are errors that happen during program execution.
  • try and except prevent your program from crashing.
  • Error handling allows you to provide helpful feedback to users.
  • A "caught" exception allows the rest of the program to continue running.

What’s Next?

In our example, we caught "any" error. But what if we want to handle a "Zero Division" differently than a "Missing File"? In Lesson 7, we’ll learn about Specific vs. Generic Exceptions!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn