Exception types in Python
The else block in exception handling runs only when the try block succeeds without raising an exception.
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)
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 |
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
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.
Mistakes Beginners Make
Expecting else to run after an exception
The else block runs only when the try block completes without raising an exception.
Fix:
Treat the matching except block as the selected path for that execution. The else block is skipped.Putting every operation in try
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.
Fix:
Keep the risky operation in try and place code that depends on its success in else.Using one response for different exception types
Different exception types can require different messages or recovery logic.
Fix:
Use separate except blocks when the program should respond differently to each exception type.Assuming every except block runs
Python executes the first matching except block and skips the remaining except blocks.
Fix:
Trace 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.
Evaluate try: The input operation completes normally, so no exception is raised.
Check except blocks: Because there is no exception to handle, both except blocks are skipped.
Run 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.
Evaluate try: The input operation raises EOFError.
Check handlers: Python checks the except blocks in order and finds the EOFError handler.
Skip 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.
Evaluate try: The input operation raises KeyboardInterrupt.
Check handlers: The EOFError handler does not match, so Python continues to the KeyboardInterrupt handler.
Skip the remaining path: After the matching handler runs, the else block is skipped.
The except KeyboardInterrupt block executes.
Key Takeaways
- The try block runs first and contains the operation that might raise an exception.
- If try succeeds, Python skips all except blocks and runs else.
- If try raises an exception, Python checks except blocks in order and runs the first matching handler.
- EOFError and KeyboardInterrupt can have separate handlers with different responses.
- The else block keeps success-path code separate from exception-handling logic.
Key Takeaways
- 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.