Concepts / Exception Handling with try and except

Exception Handling with try and except

Assertions are for development and debugging, not for handling expected runtime errors.

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

A Check Before the Next Step

Imagine that a program is about to use the first item in a list. The programmer expects the list to contain at least one item. An assert statement lets the program verify that assumption immediately. If the assumption is true, execution continues. If it is false, Python stops at the assertion and raises an AssertionError.

assert conditionevaluate conditionTrueassertion passesNext statementexecution continuesFalseassertion failsAssertionErrorprogram halts at assertionevaluatetrueevaluatefalse
What happens next when an assert condition is true versus when it is false?

How assert Verifies an Assumption

Definition

The assert statement verifies that a condition is true. Its first part is the keyword assert, followed by a condition, which can be any boolean expression. If the condition is true, the assertion passes silently and execution continues. If the condition is false, Python immediately raises an AssertionError.

python

In this example, the list has one element, so len(items) >= 1 is true. The assertion produces no output of its own, and the print statement can execute. A passing assertion is therefore silent: its effect is that execution is allowed to continue.

Output
The list contains an item.

Locating the Failure

What do you think happens?

What happens when the list is empty and execution reaches the assertion?

  • The assertion passes silently

  • The assertion raises an AssertionError

  • The assertion changes the list

  • The assertion skips to the print statement

Reveal answer
Answer:

The assertion raises an AssertionError.

An empty list makes len(items) >= 1 false. Python immediately raises an AssertionError, so execution halts at that assertion rather than reaching the next statement.

python
Output
AssertionError

The important location is the assert statement itself. Python evaluates the condition, finds it false, raises AssertionError, and stops there. The later print statement does not execute. Python also displays a traceback identifying the line that caused the problem, which helps pinpoint where the program's assumption was violated.

Create listitems = []assert conditionlen(items) >= 1AssertionErrorcondition is falseprint statementnot reachednext linefalse
How does execution move through the program, and where does it stop when an assertion fails?

Messages and Exception Handling

A custom message can be added after a comma. The message is displayed when the assertion fails, making the AssertionError more informative. It should explain which assumption mattered and what went wrong.

python
Output
AssertionError: items must contain at least one element
False conditionassertion failsAssertionErrorexception is raisedException handlingseparate from assertionpurposeproducescan be addressed by proper handling
What exception is produced by a failed assertion, and why does this matter for exception handling?

Practical Boundaries

Use an assertion when you want to verify an assumption during development or debugging, such as the expectation that a list contains at least one element. Include a descriptive message when the reason for the check may not be obvious. Do not make production-critical logic depend on an assertion: Python's -O flag can disable assertions.

  • Common mistake

    Treating a passing assertion as output.

    What it looks like

    Expecting assert len(items) >= 1 to print a confirmation when the condition is true.

    Why it fails

    A passing assertion completes silently.

    Do this instead

    Remember that a true assertion simply allows execution to continue.

  • Common mistake

    Ignoring the statement after a failed assertion.

    What it looks like

    Expecting print("The list contains an item.") to run after assert len(items) >= 1 fails.

    Why it fails

    A failed assertion raises AssertionError and halts execution at that point.

    Do this instead

    Trace the program from the failed assert; later statements are not reached.

  • Common mistake

    Using assertions for expected runtime errors.

    What it looks like

    Relying on an assertion as the production mechanism for handling a condition that may normally occur during runtime.

    Why it fails

    Assertions are a development and debugging tool, not a replacement for proper exception handling.

    Do this instead

    Use appropriate exception handling for expected runtime errors.

  • Common mistake

    Relying on assertions for production-critical logic.

    What it looks like

    Assuming an assert check will always enforce an essential production rule.

    Why it fails

    Assertions can be disabled with Python's -O flag.

    Do this instead

    Keep production-critical checks independent of assertions.

Check Your Understanding

EASY

Consider this sequence: a list is created empty, an assertion checks that its length is at least 1, and a print statement follows. Identify the condition's value, the exception produced, and whether the print statement executes. Then add a custom message that explains the violated assumption.

Hints
  • Evaluate len(items) >= 1 for an empty list.
  • A false assertion raises AssertionError.
  • Execution stops at the failed assertion, so inspect the order of the statements.
Worked example

Tracing an Empty List

Determine what happens when an empty list is checked with assert len(items) >= 1.

  1. 1
    Evaluate the condition

    The list has no elements, so the condition len(items) >= 1 is false.

  2. 2
    Raise the exception

    Because the condition is false, Python raises an AssertionError immediately.

  3. 3
    Check the next line

    Execution halts at the assertion, so a statement after it is not reached.

  4. 4
    Improve the diagnostic

    Adding a comma and a message string makes the failure explain which assumption was violated.

Result

The assertion fails at its own line, raises AssertionError, and prevents later statements from executing.

Key Takeaways

  • assert verifies that a boolean condition is true.
  • A true assertion passes silently and execution continues.
  • A false assertion immediately raises AssertionError and identifies the failure location through the traceback.
  • A comma followed by a message string makes a failed assertion more informative.
  • Assertions support development and debugging, but they should not handle expected runtime errors or enforce production-critical logic because Python's -O flag can disable them.

Related concepts

More concepts starting with E