Phase 02 · Python FoundationsLesson 7 of 8
Error & Exception Handling
Write programs that fail gracefully instead of crashing.
The problem
Things go wrong in every real program: a file is missing, a user types letters instead of a number, an API times out. Without error handling, any of these crashes your whole program. With it, your code can recover gracefully, retry, or at least fail with a clear message.
The concept
Deep dive: 2h 12m video. You don’t need it all in one sitting. Watch the first 20 minutes for the core idea, read the write-up below, and come back for the rest when you need it.
Errors vs exceptions#
- Syntax errors mean the code itself is invalid (a missing colon or bracket). Python won't run it at all.
- Exceptions happen while the program runs:
ZeroDivisionError,ValueError,FileNotFoundError,KeyErrorand so on. These are the ones you can catch.
try and except#
Put the risky code in try, and handle the failure in except:
try:
age = int(input("Your age: "))
except ValueError:
print("Please enter a whole number.")
If the conversion fails, Python jumps straight to the matching except block instead of crashing.
The full shape: else and finally#
try:
f = open("data.csv")
rows = f.readlines()
except FileNotFoundError:
print("data.csv is missing")
else:
print(f"Loaded {len(rows)} rows") # runs only if no exception
finally:
print("Done.") # always runs
| Block | Runs when |
|---|---|
try | Always, first |
except | Only if a matching exception occurs |
else | Only if no exception occurred |
finally | Always, even after errors or return. Ideal for cleanup |
The path through try, except, else and finally
tryalways runs first
- matching exception
excepte.g. "data.csv is missing"finallyalways runs
- no exception
elsee.g. "Loaded N rows"finallyalways runs
Catch specific exceptions#
# Bad: hides every possible bug
try:
process(order)
except:
pass
# Good: handle only what you expect
try:
process(order)
except KeyError as e:
print(f"Order is missing field: {e}")
Raising your own exceptions#
Use raise when your code detects a problem it can't handle:
def set_temperature(t):
if not 0 <= t <= 2:
raise ValueError("temperature must be between 0 and 2")
For larger projects, define custom exceptions so callers can handle them precisely:
class RateLimitError(Exception):
pass
Why this matters for AI work#
LLM and API calls fail regularly: rate limits, timeouts, malformed JSON in a model's reply. Production AI code wraps these calls in try/except, retries with a delay, and logs what went wrong. The patterns in this lesson are exactly what keeps an agent running when one step fails.
Try it
Your task · about 10 minutes
Ask the user for a number and keep asking until they type a valid integer, using try/except ValueError.
Recap & next
Key takeaways
- Wrap risky code in
try, and handle failures inexcept. - Catch specific exceptions (
except ValueError:) rather than a bareexcept:. elseruns only when no exception occurred;finallyalways runs, which makes it ideal for cleanup.- Use
raiseto signal errors yourself, and subclassExceptionfor custom error types.
Quick check
2 questions · instant feedback
Go deeper
Finished this lesson?
Mark it complete to track your progress and keep your streak going.