Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 101 — Programming Foundations with Python
Weeks 9–11
Exceptions, files and validated boundaries
Learning objectives
- Explain and trace the mechanisms in exceptions, files and validated boundaries.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
- Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.
Data entering a program is not correct merely because it came from a file. Establish an encoding, column names, units and a validation policy. A CSV parser handles delimiters and quoted fields; splitting each line on a comma fails when a quoted customer name itself contains a comma. Open text files with an explicit encoding and use a context manager so the file closes even when an exception occurs.
Catch errors where you can provide a meaningful response. Catching every exception and returning zero confuses a failed calculation with a successful zero result. A conversion error in an amount should identify the record for correction. A missing file is a different condition from a malformed row. Validation should preserve enough context to diagnose the problem without exposing confidential information in logs.
Design the write path as carefully as the read path. If the process overwrites the only copy and stops halfway, valid earlier data may be lost. For a local single-process application, writing a temporary file and replacing the destination after successful completion reduces this failure window. It does not by itself solve concurrent writers, operating-system durability or remote filesystem semantics. Decide whether a batch is all-or-nothing or accepts valid rows while reporting rejects. Either can be appropriate, but silently dropping records produces misleading totals. A clean separation between parsing, validation and calculation lets you test each policy independently.
Worked reasoning The parser returns the quoted company name as one field despite its internal comma. The amount is converted once at the boundary. A malformed amount raises a line-specific exception and no partial result is returned. This is an all-or-nothing in-memory parser, not a file-writing function. It allows refunds because negativity is not forbidden; that policy can be changed separately from CSV syntax.
Extended teaching and laboratory
Parsing asks whether bytes conform to a representation. Validation asks whether the represented record satisfies the domain contract. A syntactically valid CSV row can still contain an unknown customer or an invalid amount. Report the location and rule violated without leaking unrelated records.
Atomicity is a separate property. Writing each row directly to a destination while parsing can leave a partial export when a later row fails. For a modest file, validate all rows before writing. For larger data, write a temporary file, flush and close it, and replace the destination only after success. The precise durability guarantees depend on the filesystem; a successful rename should not be described as a complete backup or distributed transaction.
Worked problem A CSV export has three valid records followed by an amount field containing twelve dollars. The destination already contains yesterday’s valid report. Design failure behavior that preserves it.
Step-by-step reasoning 1. Use the CSV parser for quoting and column boundaries. The invalid amount can be identified as a numeric/domain conversion failure at its actual row, rather than a CSV quoting failure.
- Do not truncate yesterday’s file before validation. Either accumulate validated records or direct output to a separate temporary path.
- If conversion fails, discard the temporary output and return a useful error. Yesterday’s report remains the published destination.
- On success, close the output and replace the destination through the platform’s documented mechanism. Test the failure path explicitly, not only the happy path.
Failure-oriented laboratory: Atomic export and failure recovery
A successful calculation and a successful export are different events. If a process truncates the previous report before validating the new input, a later parse error can destroy the last useful artifact. Separate a pure transformation from input validation and output replacement. Validate all rows first; write the complete candidate to a temporary file in the destination directory; flush and close it; then replace the destination. A same-filesystem replacement can provide an atomic name change on supported local filesystems, but it is not a complete durability or distributed-storage guarantee.
The failure contract needs tests, not just a happy-path example. Preserve a sentinel previous report, supply an invalid late row and assert that the sentinel remains byte-for-byte unchanged. Also test a conflicting repeated event ID: identical retries may be idempotent under the chosen contract, but different events with equal values are not duplicates. An event ID repeated with changed contents should be rejected rather than silently ignored.
Use only a temporary directory and synthetic data. Inject failures at validation and immediately before replacement. Compare the observed filesystem after each failure with the documented contract. Then explain which guarantees depend on local filesystem behavior and which are established by the pure calculation tests.
Worked fixture
A synthetic ledger contains event A +100 cents, event B +100 cents and an identical retry of A. The export then encounters an invalid amount on the last row.
Explain the fixture
With event-ID idempotency, the accepted events total 200 cents before the invalid row. A policy that rejects the entire input should publish no new report, retaining the previous valid report. Deduplicating by amount would incorrectly drop B; publishing a partial total would violate the all-or-nothing input contract.
Apply the idea
A CSV export has three valid records followed by an amount field containing twelve dollars. The destination already contains yesterday’s valid report. Design failure behavior that preserves it.
A file has ten million rows, so keeping every record in memory is impractical. Propose a bounded-memory design and identify one failure that atomic replacement does not solve.
Additional laboratory — Implement two failure-injection tests and a conflict test for A repeated with +101 cents. Add a successful-run test that replaces the sentinel only after complete validation.
Read the worked reasoning
Stream parsed, validated rows into a temporary output while retaining only counters and a small error sample. Commit the output after the complete input validates, or use an explicit partial-acceptance report if that is the chosen contract. Atomic replacement does not prove the input was complete, protect against a corrupted backup, or coordinate concurrent writers. Add a run identifier and a policy for writer ownership or version conflicts.
Additional laboratory model — Both injected failures must preserve the sentinel. The conflicting ID must raise a documented validation error and leave output unchanged. A valid run must produce exactly 200 cents, and replaying the same input must not double the result. Report the tested local environment; do not claim these tests prove cross-machine crash durability.
Check understanding
Why is except Exception: return 0 dangerous here?
- It makes a failed parse look like a successful zero amount
Feedback
Failure and a valid monetary value become indistinguishable.
- It guarantees every input is validated
Feedback
Swallowing errors removes validation evidence.
- It ensures files are never overwritten
Feedback
Exception handling alone imposes no write-safety policy.
Further reading
Read the complete file and exception chapters. Implement text-file processing, handle malformed records, distinguish parsing from validation and test failure after a valid prefix. Use the Academy atomic-export laboratory to connect these mechanisms. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.