liveBook · Manning

Panic

As explained in Rust in Action: Systems programming concepts and techniques

A panic is Rust's runtime failure behavior for terminating execution after an unrecoverable program error.

A panic is Rust’s runtime response to an unrecoverable error: execution stops because the program cannot continue safely. Integer overflow and out-of-bounds array indexing are concrete triggers. section 5.2 section 2.10.1

Overflowing a u16

A u16 can represent values from 0 through 65,535. Repeatedly adding 1,000 eventually attempts an impossible value and produces an overflow panic. The diagnostic identifies the operation and can offer a backtrace through RUST_BACKTRACE=1. section 5.2

Listing 5.3 Exploring the effect of incrementing an integer past its range
 fn main() {
   let mut i: u16 = 0;
   print!("{}..", i);
 
   loop {
       i += 1000;
       print!("{}..", i);
       if i % 10000 == 0 {
           print!{"\n"}
       }
   }
 }

Run the loop to watch valid values approach the u16 limit before the addition triggers a panic. section 5.2

Panic behavior depends on the failure and execution environment:

  • Default compilation reports arithmetic overflow as a panic. section 5.2
  • Optimized compilation can produce a wrapped, incorrect result instead; adding 200 and 200 as u8 can print 144. section 5.2
  • Array indexing outside its bounds panics instead of returning erroneous data. section 2.10.1
  • A no_std program must provide its own panic handler, such as one that aborts or loops forever. section 11.2.4

Handling panic without the standard library

A kernel-style no_std program can define a #[panic_handler] that receives PanicInfo and calls intrinsics::abort(). PanicInfo includes the originating filename and line number. An infinite-loop handler is simpler but can keep a CPU core running at full utilization. section 11.2.4

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains overflow and bounds-checking triggers, optimization-dependent outcomes, diagnostics, and custom no_std handlers.
Examples
Demonstrates overflowing u16 and u8 arithmetic, out-of-bounds arrays, and aborting or looping no_std panic handlers.
What it assumes
Assumes basic Rust types and arrays while teaching integer limits, bit patterns, bounds checks, and runtime failure from concrete programs.
What you can do after
Diagnose overflow and bounds failures, inspect panic locations, and configure a panic handler for no_std programs.
How it connects
Connects panic with integer overflow, array indexing, bounds checking, the Rust runtime, the standard library, and CPU behavior.

Also explained in

Compare how 8 books explain panic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.