Writing Robust Programs with Error Handling
Try/except structures prevent program crashes by catching exceptions and executing recovery code when operations fail.
When a File Assumption Fails
A program that opens a file makes an assumption: the file exists and can be read. That assumption may be wrong. A user might enter a filename that does not exist, or the file might not be accessible. Without error handling, the program can stop with a raw traceback. A try/except structure lets the program catch the failure, explain it clearly, and end or recover in a controlled way.
What do you think happens?
A user enters a filename that does not exist. What should happen after the open operation fails?
Reveal answer
Python should jump to the except block.
When open() raises a FileNotFoundError, Python stops executing the try block and transfers control to the except block. Code after the try/except structure does not run if the except block calls exit().
Two Paths Through try and except
The try block contains the operation that might fail. Here, that operation is open(). If it succeeds, the file object is assigned to fhand, the except block is skipped, and the program continues to its file-processing loop. If open() fails because the file does not exist, it raises FileNotFoundError. Python immediately stops the try block and jumps to the except block instead.
This example follows the file-counting scenario. A successful open assigns fhand, so the later loop can examine the file and count lines beginning with Subject. A failed open sends execution to the except block. The recovery code displays the filename and calls exit(), so the loop does not attempt to use an unopened file.
Successful and Failed Opens
Tracing the Two Outcomes
Trace what happens when the user enters an existing filename and when the user enters missing.txt.
- 1Existing file
The
open()call succeeds inside the try block. fhand receives the file object, the except block is skipped, and the program proceeds to the loop that examines the file. - 2Missing file
The
open()call raisesFileNotFoundError. Python stops the try block and enters the except block. - 3Recovery
The except block prints a message containing the filename and calls
exit(). The later loop and result output are not executed.
The same program has a normal processing path for an accessible file and a controlled failure path for a missing file.
Enter a filename: missing.txt
File cannot be opened: missing.txtThe important control-flow detail is what does not happen: after the failed open, the for loop and its result output never execute. Calling exit() in the except block prevents the program from trying to process a file that was never opened.
From Traceback to Helpful Feedback
A raw Python traceback contains technical details, but it may confuse a user who only needs to know what went wrong. The except block gives the program control over its response. A message such as File cannot be opened: missing.txt identifies the failed action and the filename involved. That is more useful feedback than leaving the user with an unhandled traceback.
Mistakes That Break Recovery
Common mistake Opening the file without a try/except structure
What it looks likefhand = open(filename)Why it failsIf the file does not exist or cannot be accessed, the operation fails without recovery code and the program displays a raw traceback.
Do this insteadPlace the open() call inside a try block and handle the failure in an except block.
Common mistake Printing a message but continuing to the file-processing loop
What it looks likeexcept FileNotFoundError: print("File cannot be opened: " + filename) for line in fhand:Why it failsThe program may attempt to use fhand even though the file-opening operation failed.
Do this insteadFor this critical operation, call exit() in the except block after displaying the message.
Common mistake Showing only a raw technical error to the user
What it looks likeAllowing the failed open operation to produce an unhandled traceback.
Why it failsThe traceback contains internal technical details and does not clearly guide the user.
Do this insteadPrint a user-friendly message that explains the failure and includes the filename the user tried to open.
Practice the Control Flow
Write the missing recovery part of a program that asks for a filename, opens it inside a try block, and then processes its lines. Your recovery code should tell the user that the file cannot be opened, include the entered filename, and prevent the later processing code from running.
Hints
- The failed operation is
open(filename). - The recovery code belongs in an except block for
FileNotFoundError. - After displaying the message, use
exit()because the file is required by the later code.
- 1A robust file-reading program treats
open()as a possible failure point. The try block contains the operation, and the except block handles a failure such asFileNotFoundError. If opening succeeds, the program continues with the file object. If opening fails, the program gives the user a meaningful message and callsexit()before later file-processing code can run.
Key Takeaways
- Opening a file is an assumption that can fail when the file does not exist or cannot be accessed.
- A try/except structure catches a failed open operation and transfers control to recovery code.
- A successful open skips the except block and lets the program continue processing the file.
- A user-friendly message is more helpful than a raw Python traceback.
- When file opening is critical, call
exit()in the except block so later code does not use an unopened file.