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
tryBlock: Testing code that might fail. - The
exceptBlock: 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?
- User Experience: A friendly "File not found" message is much better than 10 lines of scary red error text.
- 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.
- 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
- Write a script that asks the user for two numbers.
- Try to divide the first number by the second.
- Use a
try-exceptblock to catch any errors. - If an error happens, print:
"Error: Calculation could not be completed." - If it works, print the result.
Quick Knowledge Check
- What is the difference between a Syntax Error and an Exception?
- What does the
tryblock do? - What happens to the code inside the
tryblock once an error occurs? - Does the code after the
try-exceptblock run if an exception is caught?
Key Takeaways
- Exceptions are errors that happen during program execution.
tryandexceptprevent 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!