Part II — Intermediate Development · Chapter 6 · Lesson 2 of 5 · 10 min read
Lesson 2: Structured Exception Handling and Recovery
Lesson level: Intermediate
Purpose: Use try, catch, finally, and throw to contain failures, preserve useful context, clean up reliably, and recover only when the program can still satisfy its contract.
Learning objectives
By the end of this lesson, you should be able to:
- explain how an exception interrupts normal control flow;
- write try/catch, try/finally, and try/catch/finally statements;
- inspect a caught error’s message and source location;
- throw deliberate domain failures;
- choose an appropriate recovery boundary;
- distinguish recovery, fallback, reclassification, and propagation;
- use finally for required cleanup without masking the primary failure;
- avoid catching failures too broadly or silently; and
- test success, handled failure, unhandled failure, and cleanup paths.
2.1 Exceptions change the path
Normal execution processes statements in source order. When a statement throws an exception, the remaining statements in that protected path are skipped. The runtime searches for a matching enclosing catch block. If none exists, the failure propagates outward and eventually reaches the caller or command-line boundary.
Exception handling does not make the failed operation succeed. It gives a defined boundary an opportunity to record context, select a safe fallback, translate the failure, or end the operation cleanly.
2.2 Core syntax
try {
# protected work
} catch err {
# recovery or translation
} finally {
# required completion work
}
A try statement requires at least a catch or a finally block. The catch name is optional. Use a name when the handler needs error details; omit it when the handler can respond without inspecting the error.
2.3 try/catch
Use try/catch when the protected operation can fail and the current layer has a meaningful response.
let result = null
let status = "pending"
try {
result = numerator / denominator
status = "complete"
} catch err {
status = "failed"
print "Calculation failed: {err.message}"
}
If division succeeds, the catch block is skipped. If it fails, assignment to status inside the try after the failing expression does not run; control moves to catch.
2.4 Caught error data
A named catch binding provides structured information including:
- message — the failure explanation;
- source — the source identity;
- line — the associated line when available; and
- column — the associated column when available.
Treat this map as diagnostic data. It does not automatically contain every category, code, stack, or host cause. The exact boundary should be documented by the runtime or host surface being used.
2.5 Catch scope
The catch binding exists only inside its catch block. Names declared inside try or catch are local to those blocks unless they update an existing outer binding.
Declare result state before the try when later code must inspect it. Avoid depending on a local variable that may never be created because the exception occurred first.
2.6 throw
Use throw to stop the current path deliberately when a contract cannot be satisfied.
if quantity < 0 {
throw "quantity must not be negative"
}
The thrown expression is evaluated and converted into an error message. Prefer concise, stable wording that identifies the violated rule. Do not include secrets or entire sensitive records.
2.7 Throw versus structured invalid result
| Situation | Prefer |
|---|---|
| One invalid record can be skipped while a batch continues | A structured invalid result |
| A required module or capability is unavailable | An exception |
| A user-entered field violates a documented rule | A validation result when expected by the contract |
| An invariant proving internal correctness is broken | An exception |
| A safe fallback fully satisfies the caller’s contract | Catch and return the documented fallback |
2.8 finally
A finally block runs after the try path, whether protected work succeeds or raises an exception. If a catch exists and handles the failure, finally runs after catch. If no catch handles it, finally still runs before the exception continues outward.
let audit_state = "started"
try {
process_record()
audit_state = "complete"
} finally {
print "Audit state: {audit_state}"
}
Use finally for completion work that must be attempted on both paths: releasing a host-managed lease, finalizing an audit marker, restoring temporary state, or recording a safe completion status.
2.9 finally does not prove success
The fact that finally ran does not mean the try block succeeded. Keep an explicit outcome variable if cleanup behavior depends on success or failure.
Do not label a transaction complete in finally unless success was recorded before leaving the protected work. Finally should observe the outcome, not invent it.
2.10 Avoid masking the primary failure
If finally throws a new exception, it may replace or obscure the original failure. Cleanup code should be small, deterministic, and independently safe.
- Do not perform unrelated business logic in finally.
- Avoid fragile network calls during mandatory cleanup.
- Preserve the original diagnostic when cleanup also fails.
- Record secondary cleanup failure through trusted observability when possible.
2.11 try/finally without catch
Use try/finally when the current layer cannot recover but must perform completion work before propagation.
try {
invoke_required_operation()
} finally {
release_local_state()
}
This pattern preserves the failure while guaranteeing that cleanup is attempted.
2.12 Recovery boundaries
Catch an exception where enough context exists to make a correct decision. A low-level helper may know how an operation failed but not whether the caller permits fallback. A service boundary may know the request contract, retry policy, and safe public response.
A good boundary is narrow enough to avoid hiding unrelated defects and high enough to choose a meaningful response.
2.13 Recovery options
| Option | Use when |
|---|---|
| Fallback | A documented alternative fully satisfies the contract |
| Skip and continue | One independent item may fail without invalidating the batch |
| Retry | The failure is transient, the operation is safe to repeat, and attempts are bounded |
| Translate | The current boundary must expose a safer or more meaningful category |
| Propagate | The current layer cannot fulfill the contract or recover safely |
| Abort | Continuing would violate consistency, security, or resource policy |
2.14 Safe fallback
A fallback must be explicit in the contract and semantically valid. Returning zero after any calculation failure is unsafe when zero could be interpreted as a real result.
Prefer a complete result that identifies fallback use:
{
"valid": true,
"value": cached_value,
"source": "cache",
"reason_code": "LIVE_SOURCE_UNAVAILABLE"
}
2.15 Retry only transient failures
Do not retry syntax errors, invalid values, missing permissions, or deterministic resource exhaustion. Retry only failures documented as transient, such as a temporary network interruption.
Every retry policy needs:
- a maximum attempt count;
- a deadline;
- an idempotency or duplicate-effect analysis;
- a delay or backoff policy when appropriate;
- clear terminal behavior; and
- observability for every attempt.
2.16 Exception handling in loops
Place try/catch inside a loop when each element is independent and one failure should not abort the batch.
for record in records {
try {
process(record)
success_count += 1
} catch err {
failure_count += 1
append(errors, {"message": err.message, "source": err.source})
}
}
Place try/catch outside the loop when any failure invalidates the entire operation. Scope expresses the failure policy.
2.17 Accounting invariants during recovery
Batch recovery needs explicit accounting:
- inspected = succeeded + failed + skipped;
- every failed record has one safe reason;
- a failed record does not contribute to successful totals;
- cleanup occurs exactly once per attempted item; and
- terminal batch status agrees with the documented tolerance policy.
2.18 Nested handlers
Nested handlers can separate local recovery from boundary translation. Keep nesting shallow. Each handler should have a distinct responsibility, such as per-record recovery inside a batch and final public mapping at the service boundary.
Do not catch the same failure repeatedly merely to print multiple messages. Preserve one coherent cause chain and use structured observability.
2.19 Recovery and partial state
An exception can occur after earlier state changes have succeeded. Before continuing, identify what was already modified and whether it can be trusted.
- Stage derived values before committing shared state.
- Update related fields together where possible.
- Use host transactions for external persistence.
- Record whether an operation was not started, partially applied, completed, or rolled back.
- Do not claim rollback unless the host confirms it.
2.20 Reclassification
A boundary may translate a low-level failure into a domain-facing message, but it should not misrepresent the cause. For example, a missing required configuration file may become a service-unavailable result, not an invalid-user-input result.
Preserve the original cause internally and use a stable outward code. Reclassification is a contract decision, not a way to hide defects.
2.21 Catching without a name
Omit the catch name when the response is independent of error details:
try {
optional_preview()
} catch {
preview_available = false
}
Use this sparingly. If the failure affects supportability or operations, record a safe diagnostic through the appropriate channel.
2.22 Common mistakes
- Catching everything around a large workflow: unrelated defects become indistinguishable.
- Ignoring the exception: silent failure destroys diagnostic evidence.
- Returning a plausible default: callers may treat fallback as real data.
- Retrying deterministic failures: attempts waste resources without changing the outcome.
- Continuing after partial mutation: state may violate invariants.
- Throwing sensitive values: messages can cross logging and service boundaries.
- Doing complex work in finally: cleanup can create a second failure.
- Setting success in finally: finally runs on both success and failure.
- Using exceptions for ordinary branching: expected decisions belong in explicit control flow.
2.23 Worked example: Fault-tolerant record normalization
A batch normalizes independent records and preserves a result for each input.
let inspected = 0
let succeeded = 0
let failed = 0
let results = []
for record in records {
inspected += 1
let item_state = "started"
try {
let normalized = normalize(record)
append(results, {"valid": true, "value": normalized})
succeeded += 1
item_state = "complete"
} catch err {
append(results, {"valid": false, "message": err.message})
failed += 1
item_state = "failed"
} finally {
print "Item state: {item_state}"
}
}
The invariant is inspected = succeeded + failed. Each attempted record appends exactly one result, and finally reports the explicit state selected by try or catch.
2.24 Recovery-design workflow
- Define the successful contract.
- List expected invalid outcomes separately from exceptional failures.
- Identify which failures are transient.
- Choose the smallest protected region.
- Decide whether the handler will recover, skip, retry, translate, or propagate.
- Identify state that may already have changed.
- Define required cleanup.
- Preserve safe diagnostic context.
- State accounting and consistency invariants.
- Test every exit path.
2.25 Guided practice
- Trace which statements run when an exception occurs midway through a try block.
- Choose between a structured invalid result and throw for five domain scenarios.
- Place a handler inside or outside a loop based on batch policy.
- Rewrite a silent catch to preserve a safe reason code.
- Explain why success must not be assigned in finally.
- Design a bounded retry policy for an idempotent network lookup.
- Identify partial state after a failure between two related assignments.
- Write an invariant for a batch with success, failure, and skip outcomes.
2.26 Hands-on lab: Build a resilient import simulator
Scenario: Process a source-defined list of import records. Each record contains an identifier, amount, category, and a flag that can simulate a provider failure.
Requirements:
- validate ordinary field errors as structured invalid results;
- throw for the simulated provider failure;
- catch provider failure per record so later records continue;
- record one complete result for every inspected record;
- track valid, invalid, provider-failed, and imported counts;
- use finally to update an attempted-item audit list exactly once;
- avoid adding failed records to imported totals;
- preserve a safe message, source, line, and column when available; and
- verify all accounting invariants.
Required cases: all valid, ordinary invalid input, provider failure in the first item, provider failure in the middle, provider failure in the last item, several failures, empty input, and a deliberately unsafe broad catch that you then correct.
Deliverable: Source, recovery policy, expected and actual results, per-record traces, cleanup evidence, invariant checks, failure catalog, and a note describing which failures would propagate in production.
2.27 Review questions
- What happens to statements after a thrown exception in the same try block?
- When does catch execute?
- What fields can a named catch binding expose?
- When does finally execute?
- Why does finally not prove success?
- When is try/finally preferable to try/catch?
- What makes a fallback safe?
- Which failures should not be retried?
- How does handler placement express batch policy?
- Why must partial state be inspected before recovery continues?
2.28 Applied challenge
Refactor the Chapter 5 Inventory Analyzer so each independent record can produce a valid result, structured invalid result, or caught exceptional result without stopping later records. Add explicit item states, cleanup evidence, accounting invariants, safe diagnostic maps, and a documented rule for failures that still abort the whole analysis.
Lesson summary
Structured exception handling separates protected work, recovery, and required completion. Catch only where the program can make a correct decision; use finally for small, reliable cleanup; throw when a contract cannot be satisfied; and preserve evidence without leaking sensitive data. Recovery must account for partial state, distinguish transient from deterministic failures, and prove consistency through explicit invariants.
Next lesson: Assertions, Invariants, and Boundary Validation
The next lesson uses assertions and explicit validation to state assumptions, protect invariants, and reject unsafe boundary data before it reaches deeper logic.
Lesson status: Ready for review.