← Fundamentals
Fundamentals

Panics, traps, and undefined behavior

Separate a checked failure, a disabled assertion and a value that no longer fits.

Classify a bad operation by its specified behavior before choosing a recovery boundary.

Outcome

Say what each language promises after a bad operation, prevent the operation where the result would be wrong, and catch or recover at the edge so one failing request does not stop the rest.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Panic
A failure that starts native panic handling. Go runs deferred calls; Rust can unwind or abort according to its panic strategy.
Undefined behaviour
An operation the language places no requirements on; the whole run may then do anything.
Defined but wrong
An operation with a guaranteed result that is still not what you meant, such as a wrapped counter.
Recover at the edge
Catching a failure once per unit of work, such as a request, so the program can continue with the next.

What the language promises after a bad operation

A checked failure follows a specified route, such as an error value, exception or panic. A trap stops execution at a runtime or machine boundary. Undefined behavior removes the language’s requirements for the affected execution, so a result observed once cannot establish a reliable rule.

Check the particular operation and build assumptions. Bounds checks, assertions and arithmetic conversions have different contracts even within one language. A useful repair enforces the application’s rule before relying on a result or continuing with later requests.

01Past the end

Resolve a requested scene

A theatre control desk resolves script scenes and processes seat-booking requests. Its legacy event encoder stores a cumulative arrival count in one unsigned octet, so values above 255 cannot be encoded. Bad scene positions, failed bookings and an unrepresentable increment require different boundaries in the same request processor.

The play has four scenes. The program prints scene 4, then asks for scene 5, then prints curtain. Predict what happens.

scenes is an array; the program reads scenes[4].

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const scenes = ["prologue", "duel", "storm", "finale"];

console.log(`scene 4: ${scenes[3]}`);
console.log(`scene 5: ${scenes[4]}`);
console.log("curtain");
What happens at scene 5?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --strict --target ES2022 --module Node16 --moduleResolution Node16 --outDir out main.ts && node out/main.js

Use a fresh directory for each supplied main file. For TypeScript, set the package.json type field to commonjs while preserving its other fields, then use the guarded compile-and-run command below. Rust commands explicitly enable unwinding, overflow checks and debug assertions for these probes. The C++ read uses at(); unchecked access is discussed without executing it.

02What the build decides

Can the desk rely on this assertion?

A rule says seats must not be negative. The program breaks the rule with seats = -1 and checks it the usual way for each language. Predict what happens.

The rule is checked with console.assert.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const seats = -1;

console.assert(seats >= 0, "seats must not be negative");

console.log(`seats ${seats}`);
What happens?

03Defined but wrong

Represent the next total

The hall counter holds one byte. It is at 250 and 10 people arrive. Predict the count.

The counter is a Uint8Array element.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const hall = new Uint8Array(1);

hall[0] = 250;
hall[0] += 10;

console.log(`in hall ${hall[0]}`);
What happens?

04Repair the theatre

Check scene numbers, keep booking, never wrap the hall count

Repair the control-desk request processor: report script positions outside the scene list, isolate each failed seat request, then encode arrival increments without wrapping the stored one-octet total.

The encoder accepts a group only when its intended cumulative total fits 0..255. Refusal leaves the prior total unchanged. This is an encoding requirement; the exercise does not calculate a venue admission policy.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.