Introduction to Exception Handling with try and except
Attempting to open a non-existent file raises a FileNotFoundError and prevents the program from obtaining a file handle.
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…
When the File Is Missing
Imagine a program asking Python to open a file that has been deleted, moved, renamed, or never created. The open() call cannot obtain a file handle for that file. Without error handling, Python stops the program and displays a traceback instead of continuing to the next statement.
What do you think happens?
A program tries to open a missing file and has no try and except block. What happens to the statement after open()?
Reveal answer
Answer: It does not run because execution stops
When open() cannot find the requested file, Python raises FileNotFoundError. Without error handling, execution stops immediately, so subsequent code does not run.
Reading the Traceback
A traceback is the error report Python displays when the program stops because of an uncaught runtime error. For a missing file, the traceback identifies where the failure occurred and names the error as FileNotFoundError. This is not a syntax mistake in the program. It is a runtime problem: the requested file is not where the program expected it to be.
- The opening line indicates that a traceback is being reported.
- The location information identifies the file and line where the failure occurred.
- The code line shows the exact open() call that failed.
- The final line names FileNotFoundError and gives details about the missing file.
What Fails Inside open()
Calling open() on a file that does not exist does not produce a usable file handle. The failure happens during the open() attempt itself. Because no handle is obtained, the program cannot proceed as though the file had been opened.
In this generated example, the first line attempts to open a file that is assumed not to exist. FileNotFoundError is raised during that attempt, so the assignment does not provide a usable file handle and the print statement is skipped when the error is not caught.
Redirecting Control with try and except
A try block contains code that might fail. A matching except block contains the response for the expected error. When the open() call inside the try block raises FileNotFoundError, Python jumps to the matching except block instead of allowing the uncaught error to terminate the program. After the except block finishes, execution continues normally.
The requested file was not found
The program continues here| Situation | What happens next |
|---|---|
| FileNotFoundError is not caught | The program stops and displays a traceback. |
| FileNotFoundError is caught by except | The except response runs, then execution continues. |
The key execution-flow difference between an uncaught and caught missing-file error.
Predicting the Next Statement
Consider the generated example in the previous section. Predict the order of the visible messages when the requested file does not exist. Which message appears first, and does the final message appear?
Hints
- The open() call is inside the try block.
- A FileNotFoundError transfers control to the matching except block.
- Execution continues after the except block completes.
Tracing a Missing-File Attempt
A program tries to open a missing file inside try, displays a response in except, and then has a statement after the exception handler. Determine the execution order.
First: Python enters the try block and attempts the open() call.
Second: The missing file causes FileNotFoundError, so statements later in the unfinished try block are skipped.
Third: Python jumps to the matching except FileNotFoundError block and runs its response.
Fourth: After the except block completes, Python continues with the statement after the exception-handling structure.
The error response runs, and the later statement also runs. The program does not stop with an uncaught traceback.
Assuming open() always produces a file handle
When open() targets a non-existent file, Python raises FileNotFoundError and does not obtain a usable file handle.
Fix:
Treat opening a file as an operation that may fail and handle FileNotFoundError when appropriate.Expecting statements after an uncaught failure to run
Without error handling, Python stops execution immediately after the error.
Fix:
Trace the program from the failing call: later statements are skipped unless the error is caught.Treating FileNotFoundError as a syntax error
FileNotFoundError is a runtime error caused by the requested file not being available at the expected location.
Fix:
Read the traceback as a report of what happened during execution.Putting the response outside the exception-handling flow
Without a matching except block, the failure remains uncaught and the program stops with a traceback.
Fix:
Place the operation that might fail in try and provide a matching except FileNotFoundError response.
Key Takeaways
- Calling open() for a non-existent file raises FileNotFoundError.
- A failed open() call does not provide a usable file handle.
- Without error handling, the traceback is displayed and subsequent code does not run.
- A try block contains the operation that might fail, while a matching except block handles FileNotFoundError.
- After the except block completes, execution continues normally.
Key Takeaways
- A missing file causes open() to raise FileNotFoundError rather than provide a file handle.
- An uncaught FileNotFoundError stops execution and produces a traceback.
- The traceback identifies the failed location, the open() statement, and the exception type.
- try and except redirect control to a matching error handler.
- Once the except block finishes, the program can continue.