Python Basics — Error Handling
1 minute read
Error Handling
Errors are a natural part of programming. Python provides a powerful and elegant exception-handling system that lets your programs deal with problems gracefully — instead of crashing.
What You’ll Learn
Quick Preview
Before Error Handling
# ❌ Program crashes instantly
age = int(input("Enter age: ")) # User types "abc" → ValueError!
print(f"You are {age}")
After Error Handling
# ✅ Program handles bad input gracefully
try:
age = int(input("Enter age: "))
except ValueError:
print("Please enter a valid number!")
else:
print(f"You are {age}")
Error Types at a Glance
| Type |
Example |
When It Happens |
SyntaxError |
if True print("hi") |
Code is malformed (caught before running) |
TypeError |
"3" + 5 |
Wrong type used in operation |
ValueError |
int("abc") |
Right type, wrong value |
KeyError |
d["missing"] |
Dictionary key doesn’t exist |
IndexError |
[1,2,3][5] |
List index out of range |
FileNotFoundError |
open("nope.txt") |
File doesn’t exist |
ZeroDivisionError |
10 / 0 |
Division by zero |
AttributeError |
"hi".append("!") |
Object lacks the attribute/method |
NameError |
print(undefined_var) |
Variable not defined |
ImportError |
import nonexistent |
Module not found |
Why Error Handling Matters
- User experience — show helpful messages, not tracebacks
- Data protection — save progress before exiting on errors
- Program resilience — recover from problems and keep running
- Debugging — log errors for later investigation
- Professional code — expected behavior for all inputs, not just happy paths
Start Learning: Exceptions Overview →