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.
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
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- 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.
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.
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.
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:
response = input("Enter your name: ")
except EOFError:
print("Input ended.")
except KeyboardInterrupt:
print("Input interrupted.")
else:
print("You entered:", response)- 1Python starts with the input operation in the try block.
- 2For ordinary text input, no exception is raised, so Python skips both except blocks and enters else.
- 3If the user sends an end-of-file signal, EOFError is raised, the EOFError handler runs, and else is skipped.
- 4If 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.
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.
| Try-block outcome | Selected block | Skipped blocks |
|---|---|---|
| The user enters text | else | All except blocks |
| The user sends an end-of-file signal | except EOFError | The other except block and else |
| The user presses Ctrl+C | except KeyboardInterrupt | The 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?
Reveal 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.
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.
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 likeThe user presses Ctrl+C, so the program runs the KeyboardInterrupt handler and then continues into else.
Why it failsThe else block runs only when the try block completes without raising an exception.
Do this insteadTreat 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 likeBoth input() and the success message are placed inside try.
Why it failsAn 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 insteadKeep 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 likeEOFError and KeyboardInterrupt are treated as though they always represent the same situation.
Why it failsDifferent exception types can require different messages or recovery logic.
Do this insteadUse separate except blocks when the program should respond differently to each exception type.
Common mistake Assuming every except block runs
What it looks likeAn EOFError occurs, so both the EOFError and KeyboardInterrupt handlers execute.
Why it failsPython executes the first matching except block and skips the remaining except blocks.
Do this insteadTrace the exception type, then stop at the first matching handler.
Trace the Input Scenarios
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.
Ordinary text input
The user enters the text Python at the input prompt.
- 1Evaluate try
The input operation completes normally, so no exception is raised.
- 2Check except blocks
Because there is no exception to handle, both except blocks are skipped.
- 3Run else
The try block succeeded, so the else block displays the entered text.
The else block executes. The EOFError and KeyboardInterrupt handlers are skipped.
End-of-file signal
The user sends an end-of-file signal while input() is waiting.
- 1Evaluate try
The input operation raises EOFError.
- 2Check handlers
Python checks the except blocks in order and finds the EOFError handler.
- 3Skip the remaining path
The KeyboardInterrupt handler and the else block are skipped.
The except EOFError block executes.
Keyboard interruption
The user presses Ctrl+C while input() is waiting.
- 1Evaluate try
The input operation raises KeyboardInterrupt.
- 2Check handlers
The EOFError handler does not match, so Python continues to the KeyboardInterrupt handler.
- 3Skip the remaining path
After the matching handler runs, the else block is skipped.
The except KeyboardInterrupt block executes.
Key Takeaways
- 1The try block runs first and contains the operation that might raise an exception.
- 2If try succeeds, Python skips all except blocks and runs else.
- 3If try raises an exception, Python checks except blocks in order and runs the first matching handler.
- 4EOFError and KeyboardInterrupt can have separate handlers with different responses.
- 5The 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.