Exceptions and Assertions
Assertions: Make Internal Assumptions Checkable
When you write a program, you rely on facts about its internal state: a count should stay nonnegative, an index should identify an existing element, or two totals should agree. An assertion is an executable check that a condition expected to hold is true at a particular point. Assertions make these expectations visible and can expose a disagreement close to where it becomes observable. The examples here use Python.
State the expected condition
Python provides this form:
assert condition, "diagnostic message"The condition is a predicate. With assertions enabled, a true condition allows execution to continue. A false condition raises AssertionError. The optional message helps explain the expectation that failed; it does not repair the state or supply a replacement value.
Write the condition as the fact you expect, rather than the error you want to detect. For example, if an internal counter must stay between zero and a capacity, including both endpoints, write:
assert 0 <= count <= capacity, "count outside capacity"A passing assertion establishes only the condition it actually checks. Checking that a count is nonnegative does not establish that it is the correct count.
Place checks where facts become known
An invariant is a property expected to hold at designated points during execution. For a job divided into completed and remaining tasks, a useful count invariant is:
You can check this relationship after an update has finished:
assert completed + remaining == planned, "task count mismatch"Example: A job contains 12 tasks. After an update, the program records 7 completed tasks and 5 remaining tasks. The sum is 12, so this assertion passes. If the program instead records 6 remaining tasks, the sum is 13 and the check fails.
Placement matters. A check before a calculation can verify an assumption needed by that calculation. A check afterward can verify an expected result. During a multi-statement update, a relationship might temporarily be false; place the check where the relationship is supposed to have been restored.
Keep checks safe to remove
Python can omit assertions when running in optimized execution. Therefore, required program behaviour must not depend on an assertion running.
Situation | Appropriate approach | Reason |
|---|---|---|
An internal update should preserve a count relationship | Assert the relationship after the update | A failure exposes an unexpected internal state |
A user may enter an unacceptable value | Perform explicit input validation | Rejection must remain active when assertions are omitted |
A calculation must update stored data | Perform the update outside the assertion | Removing a check must not remove required work |
Avoid conditions with a side effect, such as removing an item or modifying a list. Compute the result with ordinary statements, then assert a property of that result. Diagnostic messages should also avoid changing state; they are evaluated only when an enabled assertion fails.
What to remember
- Assert the condition that should be true at that point.
- Check an invariant where the program is expected to preserve it.
- Keep required validation and state changes outside assertions.
- Interpret a failure as evidence about an expectation, not proof of the mistake's exact location.
Example: Check a Warehouse Allocation
Example: A warehouse planner allocates whole items from a stock of 42 items. Its internal plan requests 13 items. The stock invariant requires the remaining count plus the allocated count to equal the starting stock. Assume all arguments are integers, available is nonnegative, assertions are enabled, and no failure handling surrounds the call.
A developer writes this function:
def allocate(available, requested):
assert 0 <= requested <= available, "request outside internal plan"
remaining = available + requested
assert remaining + requested == available, "stock count mismatch"
return remaininga) For allocate(42, 13), which assertion fails, and what values reach that check?
First check the request. Both comparisons hold because 13 is nonnegative and does not exceed 42. Execution therefore reaches the calculation of remaining.
The current calculation produces ________:
The left side of the stock check then totals ________:
The check compares 68 with 42, so its condition is false. The second assertion fails with the message stock count mismatch; the function does not return a value normally. The check exposes the inconsistent update but does not correct it.
b) Repair the stock calculation and determine the result of the same call.
Allocating items reduces available stock, so replace the addition with subtraction:
remaining = available - requestedCalculate the corrected remaining count:
Now verify the stock invariant using the corrected value:
The request check and the stock check both pass. The repaired function returns 29, representing 29 remaining items. This agrees with the practical expectation that allocating a positive number reduces the stock.
c) Using the repaired function, what happens for allocate(42, 47)?
Evaluate the first assertion before attempting the stock update. The lower comparison, zero less than or equal to 47, is true. The upper comparison, 47 less than or equal to 42, is ________. The chained condition is therefore false.
The first assertion fails with the message request outside internal plan. Execution stops before the stock calculation, so this call never computes a remaining count or reaches the second assertion. The request violates the internal plan's stated bound; no negative stock result is returned.
Match each term used when reasoning about runtime checks and error signalling with the description that fits it. Each description is used exactly once.
An except block that catches a matching error type and decides how the program continues
A guarantee about the result or state that must be true when a function returns
An object raised to signal an error condition that a caller may catch and recover from
A requirement on the inputs or state that must be true when a function is called
A property of a data structure that stays true before and after every operation on it
A runtime check of an internal assumption that holds whenever the code is correct, so a failure means a bug
Exception handler
Precondition
Exception
Invariant
Postcondition
Assertion
A dispatch program checks the following assertion with assertions enabled. Each table row represents a separate execution using item counts. Enter Pass or Fail for each row, considering only the condition shown.
assert shipped + remaining == initial, "item count mismatch"| Execution | Initial items | Shipped items | Remaining items | Assertion result |
| W | 60 | 17 | 43 | |
| X | 60 | 17 | 44 | |
| Y | 35 | 35 | 0 | |
| Z | 35 | 0 | 34 |