PeaBox Lab › PeaLang › Learn › Chapter 6 › Lesson 2

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:

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:

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

SituationPrefer
One invalid record can be skipped while a batch continuesA structured invalid result
A required module or capability is unavailableAn exception
A user-entered field violates a documented ruleA validation result when expected by the contract
An invariant proving internal correctness is brokenAn exception
A safe fallback fully satisfies the caller’s contractCatch 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.

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

OptionUse when
FallbackA documented alternative fully satisfies the contract
Skip and continueOne independent item may fail without invalidating the batch
RetryThe failure is transient, the operation is safe to repeat, and attempts are bounded
TranslateThe current boundary must expose a safer or more meaningful category
PropagateThe current layer cannot fulfill the contract or recover safely
AbortContinuing 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:

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:

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.

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

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

2.25 Guided practice

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:

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

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.

← Previous Next →