Error Handling and Debugging
22 min read
Try and Except Review
Try and Except Review
Sometimes code can fail while running.
Examples:
- User enters text instead of a number
- File does not exist
- Division by zero
Python lets us catch these errors using try and except.
You learned this before. In this lesson, we review it and improve your understanding.
Basic Structure
try:
# risky code
except:
# run if error happens
Example: Number Input
try:
age = int(input("Enter age: "))
print(age)
except:
print("Please enter a valid number")
Example Output
Enter age: hello
Please enter a valid number
How It Works
tryruns the code- If an error happens, Python jumps to
except - The program does not crash
Example: Division
try:
result = 10 / 0
print(result)
except:
print("Cannot divide by zero")
Output
Cannot divide by zero
Example: Missing File
try:
with open("data.txt") as file:
print(file.read())
except:
print("File not found")
Output
File not found
Why Use try and except?
They help you:
- Prevent crashes
- Show friendly messages
- Handle bad input
- Keep programs running
Better Practice
Catch specific errors when possible.
Instead of:
except:
Use:
except ValueError:
You will learn more in the next lesson.
Code Along
Build a safe double calculator.
Steps:
- Ask for a number
- Multiply by 2
- Handle bad input
Mini Challenge
Build a safe divider.
Steps:
- Ask for two numbers
- Divide them
- If something goes wrong, print:
Invalid operation
Expected output:
Enter first number: hi
Invalid operation
Real World Use Case
Apps use try and except for forms, login systems, files, payments, and APIs.
Quiz
- What does
trydo? - What does
exceptdo? - Why use error handling?
- What happens if no error occurs?
Assignment
Create a program that asks for a number and prints its square. Handle invalid input.
Summary
You reviewed how try and except stop crashes and help programs handle problems safely.