Skip to content

Beginning of the lesson

Exceptions in Depth

Turn crashes into controlled, recoverable events

Big idea: An exception is Python's way of signalling that something went wrong as a value that travels up the call stack. Instead of returning error codes and checking them by hand, you let the failure interrupt normal flow, then catch it exactly where you can do something useful about it. You already met try/except in the beginner course; here you will control the full lifecycle: try, except, else, finally, deliberately raise-ing errors, designing your own exception types, and chaining one failure to another.
By the end you will be able to:
  • use all four blocks — try, except, else, finally — and say what each is for,
  • catch specific exception types (and why bare except: is a trap),
  • raise exceptions on purpose, including re-raising,
  • design custom exceptions by subclassing Exception,
  • preserve the original cause with exception chaining (raise ... from ...).

1. The full anatomy: try / except / else / finally

A complete exception handler has up to four parts. Only try plus at least one except (or a finally) is required; else and finally are optional but powerful.

try:
    # 1. the risky work
    value = int(user_input)
except ValueError:
    # 2. runs ONLY if a matching exception was raised in try
    print("That was not a whole number.")
else:
    # 3. runs ONLY if try finished with NO exception
    print("You entered", value)
finally:
    # 4. ALWAYS runs — success, failure, or even return
    print("Done validating.")

The key distinction most people miss is between else and putting more code at the bottom of try:

  • try should hold only the line(s) that can fail. Keep it small so you know exactly what an except is catching.
  • except handles one kind of failure. You may have several, checked top to bottom; the first matching one wins.
  • else holds the "everything worked" follow-up. Because it runs only when try succeeded, an exception raised here is NOT caught by the except above it — that is exactly the point.
  • finally is for cleanup that must happen no matter what: closing files, releasing locks, restoring state. It runs even if you return from inside try.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers