Concepts / Exception types in Python

Exception types in Python

The central rule is simple: if the try block succeeds, Python skips the except blocks and runs else. If the try block raises an exception, Python runs the first matching except block and skips else.

  • 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 Success Path and the Error Paths

Python exception handling separates a risky operation from the responses to success and failure. The try block contains the operation that might raise an exception. One or more except blocks respond to specific exception types. An optional else block contains code that should run only when the try block completes without raising an exception.

Key point

The central rule is simple: if the try block succeeds, Python skips the except blocks and runs else. If the try block raises an exception, Python runs the first matching except block and skips else.

try blockrisky operationException raised?Matching excepterror responseelse blocksuccess responseevaluateyesno
What happens after the try block either completes normally or raises an exception?

Tracing try-except-else

Python evaluates the try block first. If no exception occurs, every except block is skipped and execution continues into else. If an exception occurs, Python immediately leaves the normal path, checks the except blocks from top to bottom, and executes the first block whose exception type matches. The else block is skipped in that case.

try beginstry succeedselse runsexception raisedexcept runsno exceptioncontinueexceptionmatch handler
How does Python decide whether execution reaches the else block or skips it?
Code walkthrough
try:
    response = input("Enter your name: ")
except EOFError:
    print("Input ended.")
except KeyboardInterrupt:
    print("Input interrupted.")
else:
    print("You entered:", response)
  1. 1
    Python starts with the input operation in the try block.
  2. 2
    For ordinary text input, no exception is raised, so Python skips both except blocks and enters else.
  3. 3
    If the user sends an end-of-file signal, EOFError is raised, the EOFError handler runs, and else is skipped.
  4. 4
    If the user presses Ctrl+C, KeyboardInterrupt is raised, its handler runs, and else is skipped.
  • The input operation is placed in try because it can produce an input-related exception.
  • EOFError has its own response.
  • KeyboardInterrupt has a separate response.
  • The else block displays the entered text only when input completed normally.
Output
If the user enters Ada:
You entered: Ada

If the user sends an end-of-file signal:
Input ended.

If the user presses Ctrl+C:
Input interrupted.

Matching Specific Exception Types

Multiple except blocks let a program give different responses to different failures. Python checks the except blocks in order from top to bottom. It executes the first block whose exception type matches the exception raised in the try block, then skips the remaining except blocks and the else block.

EOFErrorend-of-file signalEOFError handlerinput endedKeyboardInterruptCtrl+CKeyboardInterrupthandlerinput interruptedmatchesmatches
How does Python route EOFError and KeyboardInterrupt to different handlers?
Try-block outcomeSelected blockSkipped blocks
The user enters textelseAll except blocks
The user sends an end-of-file signalexcept EOFErrorThe other except block and else
The user presses Ctrl+Cexcept KeyboardInterruptThe other except block and else

The selected block depends on the outcome of the operation in try.

What do you think happens?

In the input example, suppose the user presses Ctrl+C while the input operation is waiting. Which block executes?

  • The else block

  • The except EOFError block

  • The except KeyboardInterrupt block

  • Both except blocks

Reveal answer
Answer:

The except KeyboardInterrupt block

Pressing Ctrl+C raises KeyboardInterrupt. Python checks the handlers and runs the first matching handler. Because the exception is not EOFError, the EOFError handler is skipped. The else block runs only when the try block raises no exception, so it is skipped too.

Keeping Success Code Separate

The else block is optional, but it makes the intended control flow clearer. Put the risky operation in try, put responses to its specific failures in except, and put success-path code in else. This keeps the success code separate from the code being monitored for exceptions.

You could place the success code directly after the risky operation inside try. However, any exception raised by that additional success code would also be inside the monitored try block and could be caught by the except clauses. With else, the structure communicates that the except blocks handle failures from the risky operation, while else handles the successful outcome.

Before
try:
    response = input("Enter your name: ")
    print("You entered:", response)
except EOFError:
    print("Input ended.")
except KeyboardInterrupt:
    print("Input interrupted.")

The input operation and success response are both inside try.

After
try:
    response = input("Enter your name: ")
except EOFError:
    print("Input ended.")
except KeyboardInterrupt:
    print("Input interrupted.")
else:
    print("You entered:", response)

Only the input operation is inside try; the success response is in else.

Mistakes Beginners Make

  • Common mistake

    Expecting else to run after an exception

    What it looks like

    The user presses Ctrl+C, so the program runs the KeyboardInterrupt handler and then continues into else.

    Why it fails

    The else block runs only when the try block completes without raising an exception.

    Do this instead

    Treat the matching except block as the selected path for that execution. The else block is skipped.

  • Common mistake

    Putting every operation in try

    What it looks like

    Both input() and the success message are placed inside try.

    Why it fails

    An exception from the success-path code would also occur inside the monitored try block and could be handled as though it came from the risky operation.

    Do this instead

    Keep the risky operation in try and place code that depends on its success in else.

  • Common mistake

    Using one response for different exception types

    What it looks like

    EOFError and KeyboardInterrupt are treated as though they always represent the same situation.

    Why it fails

    Different exception types can require different messages or recovery logic.

    Do this instead

    Use separate except blocks when the program should respond differently to each exception type.

  • Common mistake

    Assuming every except block runs

    What it looks like

    An EOFError occurs, so both the EOFError and KeyboardInterrupt handlers execute.

    Why it fails

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

    Do this instead

    Trace the exception type, then stop at the first matching handler.

Trace the Input Scenarios

MEDIUM

For each scenario, identify exactly one selected path: the else block, the EOFError handler, or the KeyboardInterrupt handler. Also identify which other blocks are skipped.

Hints
  • First decide whether the try block raises an exception.
  • If it does, compare the raised type with the except clauses from top to bottom.
  • The else block is possible only when no exception occurs.
Worked example

Ordinary text input

The user enters the text Python at the input prompt.

  1. 1
    Evaluate try

    The input operation completes normally, so no exception is raised.

  2. 2
    Check except blocks

    Because there is no exception to handle, both except blocks are skipped.

  3. 3
    Run else

    The try block succeeded, so the else block displays the entered text.

Result

The else block executes. The EOFError and KeyboardInterrupt handlers are skipped.

Worked example

End-of-file signal

The user sends an end-of-file signal while input() is waiting.

  1. 1
    Evaluate try

    The input operation raises EOFError.

  2. 2
    Check handlers

    Python checks the except blocks in order and finds the EOFError handler.

  3. 3
    Skip the remaining path

    The KeyboardInterrupt handler and the else block are skipped.

Result

The except EOFError block executes.

Worked example

Keyboard interruption

The user presses Ctrl+C while input() is waiting.

  1. 1
    Evaluate try

    The input operation raises KeyboardInterrupt.

  2. 2
    Check handlers

    The EOFError handler does not match, so Python continues to the KeyboardInterrupt handler.

  3. 3
    Skip the remaining path

    After the matching handler runs, the else block is skipped.

Result

The except KeyboardInterrupt block executes.

Key Takeaways

  1. 1
    The try block runs first and contains the operation that might raise an exception.
  2. 2
    If try succeeds, Python skips all except blocks and runs else.
  3. 3
    If try raises an exception, Python checks except blocks in order and runs the first matching handler.
  4. 4
    EOFError and KeyboardInterrupt can have separate handlers with different responses.
  5. 5
    The else block keeps success-path code separate from exception-handling logic.

At a glance

  • The else block runs only when the try block completes without an exception.
  • An exception selects a matching except block and causes else to be skipped.
  • Python checks multiple except blocks from top to bottom and executes the first matching one.
  • EOFError and KeyboardInterrupt can be handled separately when reading user input.
  • Keeping success code in else makes the intended control flow clearer.

Related concepts

More concepts starting with E