Concepts / Introduction to Exception Handling with try and except

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.

  • Programming
Interactive lab

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

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. 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.

Educational simulation

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()?

  • It runs normally
  • It runs only if the file handle is empty
  • It does not run because execution stops
  • It automatically creates the missing file
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.

executefile unavailableraiseskipStart programopen() callrequested fileFile not foundFileNotFoundErrorLater statementsdo not run
What happens next when open() cannot find the requested file, and which statements execute or are skipped?

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.
reportspoints tocausesTracebackerror reportLocationfile and lineopen() callfailed codeFileNotFoundErrorruntime error
How do the traceback parts identify where the failure occurred, what exception was raised, and why the program stopped?

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.

attemptraisespreventsRequested filenot foundopen()FileNotFoundErrorFile handlenot obtained
What does the program have or not have after open() fails, and why is no usable file handle obtained?
python

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.

python
Output
The requested file was not found
The program continues here
raisesmatching errorcompletestry blockopen() runsFileNotFoundErrorexcept blockresponse runsProgram continues
How does control move from the failing open() call into the matching except block, and what happens afterward?
SituationWhat happens next
FileNotFoundError is not caughtThe program stops and displays a traceback.
FileNotFoundError is caught by exceptThe except response runs, then execution continues.

The key execution-flow difference between an uncaught and caught missing-file error.

Predicting the Next Statement

EASY

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

  1. Calling open() for a non-existent file raises FileNotFoundError.
  2. A failed open() call does not provide a usable file handle.
  3. Without error handling, the traceback is displayed and subsequent code does not run.
  4. A try block contains the operation that might fail, while a matching except block handles FileNotFoundError.
  5. 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.