Concepts / Understanding Errors and Exceptions

Understanding Errors and Exceptions

try-except is an insurance policy on a sequence of statements, allowing you to respond to errors 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 a Statement Fails

Programs sometimes encounter errors while they are running. An operation may receive invalid user input, or a program may look for a file that is missing. A try-except block provides a planned response for these expected problems. Instead of allowing the error to make the program crash, the program can respond in a controlled way.

Think of try-except as an insurance policy on a sequence of statements. The try block contains the operation that might fail. The except block defines what the program should do if an exception occurs while Python is executing that operation. The block does not prevent every possible problem; it gives the program control over what happens after an expected error.

Starttry blockProtected statementsExceptionAn operation failsexcept blockError responseNext actionContinue, retry, or endgracefullyexception occursjumpafter handling
What happens next when a statement in the try block raises an exception?

The Two Execution Paths

What do you think happens?

A try block contains several statements. What happens to the statements after the one that causes an exception?

  • They continue immediately before the except block runs

  • They are skipped, and execution moves to the except block

  • They run twice after the except block finishes

Reveal answer
Answer:

They are skipped, and execution moves to the except block.

Python executes the try block first. When an exception occurs, execution jumps to the except block rather than continuing through the remaining statements in the try block.

There are two main paths through a try-except structure. If every statement in the try block succeeds, Python finishes the try block and skips the except block. If a statement in the try block causes an exception, Python stops following the remaining statements in that try block and jumps to the except block.

try blockAll statements succeedNext statementexcept is skippedtry blockAn exception occursexcept blockError response runsNext actionAfter handlingcomplete normallyjumpafter response
How does control flow differ when all statements succeed versus when an exception occurs?
Worked example

Checking an Input Operation

Predict the path for a program that places an operation involving user input inside a try block. Consider both valid and invalid input.

  1. 1
    Begin with the try block

    Python starts by executing the statements in the try block.

  2. 2
    Valid input

    If the input is valid and no exception occurs, Python completes the try block and skips the except block.

  3. 3
    Invalid input

    If the input is invalid and an exception occurs, Python stops the try block at that point and jumps to the except block.

  4. 4
    After the response

    The except block gives the program control over what happens next. It can support fixing the problem, trying again, or ending gracefully.

Result

Success follows the normal path and skips except. Failure leaves the try block and runs except instead.

Roles of the Two Blocks

Definition

The try block is the sequence of statements that Python attempts to execute first. The except block is the response that Python runs when an exception occurs in the try block.

tryBegins protected sequenceStatementsOperation that might failexceptBegins error responseResponseWhat happens after anexceptioncontainsexception sends control todefines
What contains the operation that might fail, and where is the response defined?
Best practice

Keep the try block focused on the operation that might fail. A focused block makes it clearer which operation is being protected and what the except block is responding to.

After the Exception Is Handled

Catching an exception gives the program control over what happens next. The response can address the problem, arrange for the operation to be tried again, or finish the program gracefully. Handling an exception therefore changes the program from an uncontrolled failure into a planned path.

ExceptionExpected problemexcept blockControlled responseFix problemTry againEnd gracefullyjumpoptionoptionoption
Where can execution go after the except block runs?
Worked example

A Missing File

A program attempts to use a file that may not exist. Explain how try-except changes the outcome.

  1. 1
    Protect the file operation

    Place the operation that might encounter the missing file in the try block.

  2. 2
    File is available

    The operation succeeds, so Python completes the try block and skips the except block.

  3. 3
    File is missing

    The operation causes an exception, so Python stops the try block and jumps to the except block.

  4. 4
    Choose a controlled response

    The except block can provide a response, support another attempt, or allow the program to end gracefully.

Result

The file operation follows the normal path when it succeeds and follows the exception-handling path when the file is missing.

Expected errorNo planned responseCrashExpected errorInside try blockexcept responsePlanned handlingGraceful endOr another planned actionunhandledcaughtcontrolled outcome
How does catching an expected error change the program's behavior?

Mistakes to Avoid

  • Common mistake

    Assuming the except block always runs

    What it looks like

    The try block completes without an exception, but the learner expects the error response to run anyway.

    Why it fails

    Python skips the except block when no exception occurs.

    Do this instead

    Trace the try block first. Run the except path only when an exception occurs.

  • Common mistake

    Expecting the remaining try statements to run after an exception

    What it looks like

    A statement near the beginning of the try block fails, but the learner expects later statements in that block to execute.

    Why it fails

    When an exception occurs, Python jumps to the except block.

    Do this instead

    Mark the failing statement, stop tracing the rest of the try block, and continue with except.

  • Common mistake

    Putting unrelated operations in the try block

    What it looks like

    Several different operations are placed together even though only one is expected to fail.

    Why it fails

    A broad block makes it less clear which operation might have caused the exception.

    Do this instead

    Keep the try block focused on the operation that might fail.

  • Common mistake

    Using try-except without a planned response

    What it looks like

    An expected input or file problem is caught, but the program has no clear next action.

    Why it fails

    Catching an exception is useful because it gives control over what happens next.

    Do this instead

    Decide whether the program should fix the problem, try again, or end gracefully.

Trace It Yourself

MEDIUM

Imagine a focused try block containing an operation that might fail, followed by an except block containing a controlled response. Trace these cases: the operation succeeds; the operation raises an exception; and the except response allows the program to try again. For each case, identify which block runs first, whether the except block runs, and what the program can do next.

Hints
  • Python always begins by executing the try block.
  • If no exception occurs, the except block is skipped.
  • If an exception occurs, stop tracing the remaining try statements and move to the except block.
  • After handling the exception, the program can fix the problem, try again, or end gracefully.
SituationTry blockExcept blockPossible next result
No exception occursCompletesSkippedNormal execution continues
An exception occursStops at the failing operationRunsProblem is fixed, another attempt is made, or the program ends gracefully

A control-flow checklist for tracing a try-except block.

Key Takeaways

  1. 1
    Python executes the try block first.
  2. 2
    If no exception occurs, the except block is skipped.
  3. 3
    If an exception occurs, Python jumps from the try block to the except block and skips the remaining try statements.
  4. 4
    Try-except is suited to expected problems such as invalid user input or missing files.
  5. 5
    Handling an exception gives the program control to fix the problem, try again, or end gracefully.

At a glance

  • A try-except block protects a sequence of statements with a planned error response.
  • A successful try block skips except; an exception sends control to except.
  • Statements remaining in the try block after the exception are skipped.
  • Keep the try block focused on an expected operation that might fail.
  • After handling an exception, a program can fix the problem, try again, or end gracefully.

More concepts starting with U