📌 Quick Info
- Topic: Error handling in Python
- Target Audience: Beginners who've seen error messages but don't know how to handle them
- Goal: Stop being scared of errors and start handling them gracefully
1. Introduction
"The first time I saw a red error message in Python, I panicked. Now I read them like a map. Here's how I stopped being scared of errors — and started using try/except to handle them properly."
2. The Problem (When Code Crashes)
age = int(input("Enter your age: "))
print(f"You are {age} years old")
What happens if the user types “Twenty”?
ValueError:invalid literal for int() with base 10:'twenty'
The whole program crashes. One wrong input and everything stops.
3. The Solution (try/expect)
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("Please enter a number, not text.")
Output (if user types “twenty”):
Please enter a number, not text.
The program keeps running. No Crash.
4. How It Works (Line by Line)
Line 1: try: — "Python, try running this code."
Line 2-3: The code that might fail.
Line 4: except ValueError: — "If a ValueError happens, do this instead."
Line 5: The fallback message.
If no error happens, the except block is skipped entirely.
5. Catching Multiple Errors
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero.")
except TypeError:
print("Wrong type of value.")
Output:
You can't divide by zero.
6. The finally Block
finally runs no matter what- error or no error:
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Done trying to read the file.")
Output (if file missing):
File not found
Done trying to read the file.
Great for cleanup- closing files, releasing connections, etc.
7. Common Beginner Mistakes
Mistake 1: Catching everything
try:
# any code
except:
pass
This hides real bugs. Catch specific exceptions.
Mistake 2: Using an empty except block
except ValueError:
pass # silently ignores the error
At minimum, print or log something. Never swallow errors silently.
Mistake 3: Using try/except for control flow
Don’t wrap every line in try/except “just in case.” Only wrap code that might realistically fail.
8. Real Example (My Practise)
def get_number():
while True:
try:
return int(input("Enter a number: "))
except ValueError:
print("That's not a number. Try again.")
number = get_number()
print(f"You entered: {number}")
Behavior: It keeps asking until the user types a valid number.
9. What I Learned
· Errors aren’t failures — they’re Python telling you what went wrong
· try/except lets your program recover instead of crashing
· Catch specific exceptions, not everything
· finally runs whether or not there’s an error
· Never silently swallow errors — always log or print something
10. Conclusion
"Error handling felt like extra work at first. Now I add it the same way I add comments — because I know future me will thank present me. A program that handles errors gracefully is a program people actually trust."
Top comments (0)