Skip to content

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

PythonPython not started

Catch the exception you expect, by name. Which name? Let the failure tell you:

PythonPython not started

Never catch everything

PythonPython not started

except Exception swallows the typo in your own code just as happily as the malformed input it was meant for. Name what you expect:

PythonPython not started

else and finally

else runs when nothing was raised. finally runs either way, and is where cleanup goes:

PythonPython not started

Keeping the risky line alone in the try and the rest in else is what stops you catching an exception you never meant to:

PythonPython not started

Raising

Raise when a caller has given you something you cannot work with:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

A retry loop

The pattern you will write for every API client. The point is that only some failures are worth retrying:

PythonPython not started

Reading a traceback

Read it bottom-up: the last line is what went wrong, and the frame above it is where:

PythonPython not started

Try it yourself

Exercise 1

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.

Your turnPython not started
Exercise 2

Complete extract_text: raise MalformedResponse for a reply that is not JSON or has no content key, keeping the original exception as the cause.

Your turnPython not started

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 Exception hides your own bugs; a bare except: also breaks Ctrl+C.
  • Keep the risky line alone in try, put the follow-on work in else, and put cleanup in finally.
  • 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 error keeps 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.