Concepts / Finally blocks for cleanup code

Finally blocks for cleanup code

The else block in exception handling runs only when the try block succeeds without raising an exception.

  • Programming

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.

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

Tracing Successful and Failed Paths

execution completesraisesraisesyesmatchesmatchestry blockNo exceptionelse blockrunsEOFErrorEOFError handlerrunsKeyboardInterruptKeyboardInterrupthandlerruns
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.

raises EOFErrorraises KeyboardInterruptmatchesmatchesInput operationinside tryEOFError handlerchecked firstEOFError responseKeyboardInterrupthandlerchecked nextKeyboardInterruptresponse
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.

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.

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

End-of-file signal: The input operation raises EOFError. Python selects the EOFError handler, skips the other except block, and skips else.

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

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

  • Assuming else runs after every try block

    Else runs only when try completes without raising an exception.

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

  • Treating multiple except blocks as cumulative

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

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

  • Putting all success logic inside try without considering its monitoring scope

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

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

  • Confusing an exception type with the success case

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

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

Execution Rules to Remember

  1. Python evaluates the try block first.
  2. A successful try skips every except block and enters else.
  3. An exception in try sends control to the first except block that matches its type.
  4. After one except block matches, the remaining except blocks and else are skipped.
  5. Use separate except blocks when different exception types need different responses.
  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.