Concepts / Introduction to Exception Handling with try and except

Introduction to Exception Handling with try and except

Handling FileNotFoundError lets a program inform the user, ask for a different filename, use a default file, or take another sensible action instead of crashing.

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

Start programopen() callrequested fileFile not foundFileNotFoundErrorLater statementsdo not runexecutefile unavailableraiseskip
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.
Tracebackerror reportLocationfile and lineopen() callfailed codeFileNotFoundErrorruntime errorreportspoints tocauses
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.

Requested filenot foundopen()FileNotFoundErrorFile handlenot obtainedattemptraisesprevents
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
try blockopen() runsFileNotFoundErrorexcept blockresponse runsProgram continuesraisesmatching errorcompletes
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.
Worked example

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.

  1. 1
    First

    Python enters the try block and attempts the open() call.

  2. 2
    Second

    The missing file causes FileNotFoundError, so statements later in the unfinished try block are skipped.

  3. 3
    Third

    Python jumps to the matching except FileNotFoundError block and runs its response.

  4. 4
    Fourth

    After the except block completes, Python continues with the statement after the exception-handling structure.

Result

The error response runs, and the later statement also runs. The program does not stop with an uncaught traceback.

  • Common mistake

    Assuming open() always produces a file handle

    What it looks like

    The program proceeds as though the file was opened even though the requested file is missing.

    Why it fails

    When open() targets a non-existent file, Python raises FileNotFoundError and does not obtain a usable file handle.

    Do this instead

    Treat opening a file as an operation that may fail and handle FileNotFoundError when appropriate.

  • Common mistake

    Expecting statements after an uncaught failure to run

    What it looks like

    A print statement placed after a failing open() call is expected to execute.

    Why it fails

    Without error handling, Python stops execution immediately after the error.

    Do this instead

    Trace the program from the failing call: later statements are skipped unless the error is caught.

  • Common mistake

    Treating FileNotFoundError as a syntax error

    What it looks like

    The traceback is interpreted as evidence that the Python statement was written with invalid syntax.

    Why it fails

    FileNotFoundError is a runtime error caused by the requested file not being available at the expected location.

    Do this instead

    Read the traceback as a report of what happened during execution.

  • Common mistake

    Putting the response outside the exception-handling flow

    What it looks like

    The program has no matching except block for FileNotFoundError.

    Why it fails

    Without a matching except block, the failure remains uncaught and the program stops with a traceback.

    Do this instead

    Place the operation that might fail in try and provide a matching except FileNotFoundError response.

Key Takeaways

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

At a glance

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

Related concepts

More concepts starting with I