Core Python·Lesson 15 of 67·intermediate
Exceptions and defensive code
try, except, else and finally — plus custom exception classes, chaining with raise from, and the retry loop every API client eventually needs.
In this lesson · 18 min
- →Catch specific exceptions and explain why a bare except is a bug
- →Use else and finally correctly
- →Raise your own exceptions, including custom classes
- →Preserve the original cause with raise ... from
- →Write a retry loop that distinguishes retryable failures from permanent ones
Code that talks to the outside world fails. Files go missing, JSON arrives malformed, an API returns 429. Exceptions are how Python reports that, and handling them precisely is the difference between a pipeline that recovers and one that hides a bug for a week.
try and except
Catch the exception you expect, by name. Which name? Let the failure tell you:
Never catch everything
except Exception swallows the typo in your own code just as happily as the malformed input it
was meant for. Name what you expect:
else and finally
else runs when nothing was raised. finally runs either way, and is where cleanup goes:
Keeping the risky line alone in the try and the rest in else is what stops you catching an
exception you never meant to:
Raising
Raise when a caller has given you something you cannot work with:
Pick the exception that already means what you mean: ValueError for a bad value,
TypeError for a bad type, KeyError for a missing key, FileNotFoundError for a missing file.
Your own exception classes
When callers need to handle your failure specifically, give it a class. A shared base class lets them catch the whole family at once:
raise … from
When you catch one failure and raise another, from keeps the original attached, so the
traceback shows both. Without it, the real cause is guesswork:
Ask forgiveness, not permission
Python prefers trying the operation to checking first. Checking first is both slower and racy — the file can vanish between the check and the open:
A retry loop
The pattern you will write for every API client. The point is that only some failures are worth retrying:
Reading a traceback
Read it bottom-up: the last line is what went wrong, and the frame above it is where:
Try it yourself
Write to_float(value, default=0.0): return the value as a float, or default when it cannot be converted. Catch only the exceptions that conversion actually raises.
Complete extract_text: raise MalformedResponse for a reply that is not JSON or has no content key, keeping the original exception as the cause.
Check yourself
An API client retries every exception it sees, up to five times. What is the cost of that?
Check yourself
What does the `from error` in `raise MalformedResponse('bad') from error` do?
Recap
- Catch the specific exception you expect.
except Exceptionhides your own bugs; a bareexcept:also breaks Ctrl+C. - Keep the risky line alone in
try, put the follow-on work inelse, and put cleanup infinally. - Raise the built-in that already means what you mean; define a class when callers need to handle your failure specifically, with a shared base for the family.
raise X from errorkeeps the original cause in the traceback.- Python prefers trying over checking — one operation, no race.
- Split API failures into retryable and permanent, and back off exponentially between attempts.