Concepts / Finally blocks for cleanup code

Finally blocks for cleanup code

The else block means: continue with this code only after the try block has succeeded.

  • Programming
Interactive lab

Try it: try / except / else / finally

How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.

How it works

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. finally runs in every case.

Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.

Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.

Educational simulation

Loading the simulation…

The Path Depends on the Try Block

Exception handling has a success path and one or more error paths. The try block runs first. If it completes without raising an exception, Python skips the except blocks and runs the else block. If the try block raises an exception, Python jumps to the first matching except block and skips the else block.

Key point

The else block means: continue with this code only after the try block has succeeded.

Tracing Successful and Failed Paths

try blockNo exceptionelse blockrunsEOFErrorEOFError handlerrunsKeyboardInterruptKeyboardInterrupthandlerrunsexecution completesraisesraisesyesmatchesmatches
What code block executes next when the try block succeeds, raises EOFError, or raises KeyboardInterrupt?

Think of the try block as the decision point. Python evaluates it before considering the rest of the structure. A normal completion takes the success route to else. An exception takes an error route to a matching except block. These routes do not merge into else: when an exception occurs, else is skipped.

  • Try succeeds: except blocks are skipped, then else runs.
  • Try raises a handled exception: Python enters the first matching except block, and else is skipped.
  • Try raises EOFError: the EOFError handler runs if one is present.
  • Try raises KeyboardInterrupt: the KeyboardInterrupt handler runs if one is present.

Separate Handlers for Specific Interruptions

Multiple except blocks allow different exception types to receive different responses. Python checks the except blocks from top to bottom and executes the first one whose exception type matches the raised exception. After that matching handler is selected, the remaining except blocks are skipped.

Input operationinside tryEOFError handlerchecked firstEOFError responseKeyboardInterrupthandlerchecked nextKeyboardInterruptresponseraises EOFErrorraises KeyboardInterruptmatchesmatches
How does control flow branch from the try block into separate EOFError and KeyboardInterrupt handlers?

A user-input operation can be interrupted in more than one way. An end-of-file signal raises EOFError, while pressing Ctrl+C raises KeyboardInterrupt. Separate handlers let the program provide a tailored response for each case. In this example, the two exception types are independent, so either order would work. In general, order matters when exception types overlap through inheritance.

Situation in tryBlock selectedElse block
The user enters ordinary textelseRuns
The user sends an end-of-file signalEOFError handlerSkipped
The user presses Ctrl+CKeyboardInterrupt handlerSkipped

The selected path depends on what happens during the input operation.

Why Success Code Belongs in Else

The else block is optional, but it separates success-path logic from exception-handling logic. Code in try is monitored for exceptions. If success code is placed in try after the risky operation, an exception accidentally raised by that success code could also be caught by the except blocks. That may not be the intended behavior. Code in else runs only after the try block has completed successfully, so the structure communicates which statements belong to the risky operation and which belong to the success case.

Worked example

Reading user input

Determine the selected path when a program attempts to read input and the user either enters text, sends an end-of-file signal, or presses Ctrl+C.

  1. 1
    Ordinary text

    The input operation completes without an exception. The except blocks are skipped, and the else block runs to display what was entered.

  2. 2
    End-of-file signal

    The input operation raises EOFError. Python selects the EOFError handler, skips the other except block, and skips else.

  3. 3
    Ctrl+C

    The input operation raises KeyboardInterrupt. Python selects the KeyboardInterrupt handler, skips the other except block, and skips else.

Result

Only ordinary text reaches else. Each interruption reaches its corresponding specific except block.

Predicting the Selected Block

What do you think happens?

A program tries to read user input. The user enters ordinary text rather than sending an end-of-file signal or pressing Ctrl+C. Which path executes?

  • Only the EOFError handler

  • Only the KeyboardInterrupt handler

  • The else block

  • Both except blocks and the else block

Reveal answer
Answer:

The else block

The try operation completes without raising an exception, so Python skips both except blocks and runs else.

What do you think happens?

The input operation raises EOFError. Which blocks are skipped after Python selects the EOFError handler?

  • Only the KeyboardInterrupt handler

  • The KeyboardInterrupt handler and the else block

  • Only the else block

  • No blocks are skipped

Reveal answer
Answer:

The KeyboardInterrupt handler and the else block

Python runs the first matching except block. The remaining except blocks are skipped, and else runs only when try succeeds.

EASY

For each scenario, name the block that executes next: the user presses Ctrl+C; the user enters text; the input operation raises EOFError.

Hints
  • Check first whether the try operation raises an exception.
  • Match EOFError and KeyboardInterrupt to their specific handlers.
  • Use else only for the scenario with no exception.

Mistakes in Control-Flow Reasoning

  • Common mistake

    Assuming else runs after every try block

    What it looks like

    The try block raises EOFError, but the learner expects the else block to display the result.

    Why it fails

    Else runs only when try completes without raising an exception.

    Do this instead

    Follow the exception path to the matching except block and mark else as skipped.

  • Common mistake

    Treating multiple except blocks as cumulative

    What it looks like

    The learner expects both the EOFError and KeyboardInterrupt handlers to run after one exception.

    Why it fails

    Python executes the first matching except block and skips the remaining except blocks.

    Do this instead

    Check the except blocks from top to bottom and stop at the first match.

  • Common mistake

    Putting all success logic inside try without considering its monitoring scope

    What it looks like

    A success-path statement placed after the risky operation raises an exception and is caught by the same except blocks.

    Why it fails

    Everything in try is monitored for exceptions, not only the initial risky operation.

    Do this instead

    Use else for code that depends on the try block succeeding.

  • Common mistake

    Confusing an exception type with the success case

    What it looks like

    Treating ordinary input as though it selected an exception handler.

    Why it fails

    Ordinary input does not raise EOFError or KeyboardInterrupt in the described scenario.

    Do this instead

    When no exception occurs, skip the except blocks and continue to else.

Execution Rules to Remember

  1. 1
    Python evaluates the try block first.
  2. 2
    A successful try skips every except block and enters else.
  3. 3
    An exception in try sends control to the first except block that matches its type.
  4. 4
    After one except block matches, the remaining except blocks and else are skipped.
  5. 5
    Use separate except blocks when different exception types need different responses.
  6. 6
    Use else for success-path code that should remain separate from monitored, potentially risky code.

Key Takeaways

  • The else block runs only when the try block succeeds without raising an exception.
  • When try raises an exception, Python checks except blocks in order and executes the first matching handler.
  • EOFError and KeyboardInterrupt can have separate handlers with different responses.
  • The else block keeps success logic separate from exception-handling logic.
  • For ordinary input, the success path reaches else; for the two described interruptions, the matching except path runs.

Related concepts

More concepts starting with F