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







