Understanding Errors and Exceptions
try-except is an insurance policy on a sequence of statements, allowing you to respond to errors instead of crashing.
When a Statement Fails
Programs sometimes encounter errors while they are running. An operation may receive invalid user input, or a program may look for a file that is missing. A try-except block provides a planned response for these expected problems. Instead of allowing the error to make the program crash, the program can respond in a controlled way.
Think of try-except as an insurance policy on a sequence of statements. The try block contains the operation that might fail. The except block defines what the program should do if an exception occurs while Python is executing that operation. The block does not prevent every possible problem; it gives the program control over what happens after an expected error.
The Two Execution Paths
What do you think happens?
A try block contains several statements. What happens to the statements after the one that causes an exception?
Reveal answer
Answer: They are skipped, and execution moves to the except block.
Python executes the try block first. When an exception occurs, execution jumps to the except block rather than continuing through the remaining statements in the try block.
There are two main paths through a try-except structure. If every statement in the try block succeeds, Python finishes the try block and skips the except block. If a statement in the try block causes an exception, Python stops following the remaining statements in that try block and jumps to the except block.
Checking an Input Operation
Predict the path for a program that places an operation involving user input inside a try block. Consider both valid and invalid input.
Begin with the try block: Python starts by executing the statements in the try block.
Valid input: If the input is valid and no exception occurs, Python completes the try block and skips the except block.
Invalid input: If the input is invalid and an exception occurs, Python stops the try block at that point and jumps to the except block.
After the response: The except block gives the program control over what happens next. It can support fixing the problem, trying again, or ending gracefully.
Success follows the normal path and skips except. Failure leaves the try block and runs except instead.
Roles of the Two Blocks
The try block is the sequence of statements that Python attempts to execute first. The except block is the response that Python runs when an exception occurs in the try block.
Keep the try block focused on the operation that might fail. A focused block makes it clearer which operation is being protected and what the except block is responding to.
After the Exception Is Handled
Catching an exception gives the program control over what happens next. The response can address the problem, arrange for the operation to be tried again, or finish the program gracefully. Handling an exception therefore changes the program from an uncontrolled failure into a planned path.
A Missing File
A program attempts to use a file that may not exist. Explain how try-except changes the outcome.
Protect the file operation: Place the operation that might encounter the missing file in the try block.
File is available: The operation succeeds, so Python completes the try block and skips the except block.
File is missing: The operation causes an exception, so Python stops the try block and jumps to the except block.
Choose a controlled response: The except block can provide a response, support another attempt, or allow the program to end gracefully.
The file operation follows the normal path when it succeeds and follows the exception-handling path when the file is missing.
Mistakes to Avoid
Assuming the except block always runs
Python skips the except block when no exception occurs.
Fix:
Trace the try block first. Run the except path only when an exception occurs.Expecting the remaining try statements to run after an exception
When an exception occurs, Python jumps to the except block.
Fix:
Mark the failing statement, stop tracing the rest of the try block, and continue with except.Putting unrelated operations in the try block
A broad block makes it less clear which operation might have caused the exception.
Fix:
Keep the try block focused on the operation that might fail.Using try-except without a planned response
Catching an exception is useful because it gives control over what happens next.
Fix:
Decide whether the program should fix the problem, try again, or end gracefully.
Trace It Yourself
Imagine a focused try block containing an operation that might fail, followed by an except block containing a controlled response. Trace these cases: the operation succeeds; the operation raises an exception; and the except response allows the program to try again. For each case, identify which block runs first, whether the except block runs, and what the program can do next.
Hints
- Python always begins by executing the try block.
- If no exception occurs, the except block is skipped.
- If an exception occurs, stop tracing the remaining try statements and move to the except block.
- After handling the exception, the program can fix the problem, try again, or end gracefully.
| Situation | Try block | Except block | Possible next result |
|---|---|---|---|
| No exception occurs | Completes | Skipped | Normal execution continues |
| An exception occurs | Stops at the failing operation | Runs | Problem is fixed, another attempt is made, or the program ends gracefully |
A control-flow checklist for tracing a try-except block.
Key Takeaways
- Python executes the try block first.
- If no exception occurs, the except block is skipped.
- If an exception occurs, Python jumps from the try block to the except block and skips the remaining try statements.
- Try-except is suited to expected problems such as invalid user input or missing files.
- Handling an exception gives the program control to fix the problem, try again, or end gracefully.
Key Takeaways
- A try-except block protects a sequence of statements with a planned error response.
- A successful try block skips except; an exception sends control to except.
- Statements remaining in the try block after the exception are skipped.
- Keep the try block focused on an expected operation that might fail.
- After handling an exception, a program can fix the problem, try again, or end gracefully.