Concepts / Writing Robust Programs with Error Handling

Writing Robust Programs with Error Handling

Try/except structures prevent program crashes by catching exceptions and executing recovery code when operations fail.

  • Programming

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?

  • The program should continue to the file-processing loop
  • Python should jump to the except block
  • The program should pretend that an empty file was opened
Reveal answer

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

succeedscontinuefailscaughtrecoverFilename enteredopen(filename)inside tryFile objectfhand assignedCount Subject linesfor loopFileNotFoundErroropen failsexcept blockrecovery codeHelpful messagethen exit()
What happens next when opening a file succeeds versus when it raises an exception?

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.

python

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.

Existing 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.

Missing file: The open() call raises FileNotFoundError. Python stops the try block and enters the except block.

Recovery: 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.

failscaught by exceptexit()open(filename)FileNotFoundErrorFile cannot be openedincludes filenameProgram endsexit()
After an exception is caught, what recovery actions occur before the program ends?
Output
Enter a filename: missing.txt
File cannot be opened: missing.txt

The 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

unhandled failureexcept recoveryRaw tracebacktechnical detailsConfused userFile cannot beopenedincludes filenameClean terminationexit()
How does a technical exception message change into feedback that a user can understand?

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

  • Opening the file without a try/except structure

    If the file does not exist or cannot be accessed, the operation fails without recovery code and the program displays a raw traceback.

    Fix: Place the open() call inside a try block and handle the failure in an except block.

  • Printing a message but continuing to the file-processing loop

    The program may attempt to use fhand even though the file-opening operation failed.

    Fix: For this critical operation, call exit() in the except block after displaying the message.

  • Showing only a raw technical error to the user

    The traceback contains internal technical details and does not clearly guide the user.

    Fix: Print a user-friendly message that explains the failure and includes the filename the user tried to open.

Practice the Control Flow

EASY

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.
  1. A 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 as FileNotFoundError. If opening succeeds, the program continues with the file object. If opening fails, the program gives the user a meaningful message and calls exit() 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.