Exception Handling with try and except
Assertions are for development and debugging, not for handling expected runtime errors.
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…
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.
How assert Verifies an Assumption
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.
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.
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?
Reveal 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.
AssertionErrorThe 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.
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.
AssertionError: items must contain at least one elementPractical 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 likeExpecting assert len(items) >= 1 to print a confirmation when the condition is true.
Why it failsA passing assertion completes silently.
Do this insteadRemember that a true assertion simply allows execution to continue.
Common mistake Ignoring the statement after a failed assertion.
What it looks likeExpecting print("The list contains an item.") to run after assert len(items) >= 1 fails.
Why it failsA failed assertion raises
AssertionErrorand halts execution at that point.Do this insteadTrace the program from the failed assert; later statements are not reached.
Common mistake Using assertions for expected runtime errors.
What it looks likeRelying on an assertion as the production mechanism for handling a condition that may normally occur during runtime.
Why it failsAssertions are a development and debugging tool, not a replacement for proper exception handling.
Do this insteadUse appropriate exception handling for expected runtime errors.
Common mistake Relying on assertions for production-critical logic.
What it looks likeAssuming an assert check will always enforce an essential production rule.
Why it failsAssertions can be disabled with Python's -O flag.
Do this insteadKeep production-critical checks independent of assertions.
Check Your Understanding
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.
Tracing an Empty List
Determine what happens when an empty list is checked with assert len(items) >= 1.
- 1Evaluate the condition
The list has no elements, so the condition
len(items)>= 1 is false. - 2Raise the exception
Because the condition is false, Python raises an
AssertionErrorimmediately. - 3Check the next line
Execution halts at the assertion, so a statement after it is not reached.
- 4Improve the diagnostic
Adding a comma and a message string makes the failure explain which assumption was violated.
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
AssertionErrorand 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.