Panic and Unwinding | Rust Fundamentals lesson | BraveProgrammer
Lesson 20 of 50
·rust
Panic and Unwinding
12 minutes
Course progress40%
Panic and Unwinding
A panic is an unrecoverable error that terminates the program (or thread). Rust provides the panic! macro and strategies for handling panics.
The Panic Macro
fnmain() {
panic!(\"Something went very wrong!\");
// This line never executes
}
Output:
thread 'main' panicked at 'Something went very wrong!', src/main.rs:2:5
Panic From Unwrapping
Common ways panics occur:
fnmain() {
letx: Option<i32> = None;
letval = x.unwrap(); // panics: called `Option::unwrap()` on a `None` valueletv = vec![1, 2, 3];
letitem = v[10]; // panics: index out of boundsletnums = \"abc\";
let result: i32 = nums.parse().unwrap(); // panics: invalid digit
}
When to Panic
Good Uses
Unrecoverable errors: No sensible recovery available
Development: Assert assumptions in tests
Examples/Prototypes: Simplify code for clarity
Bad Uses
Expected failures: Should use Result instead
File not found: Use Result and handle gracefully
Invalid input: Validate and return error
Assertions
Assert conditions hold, panic if they don't:
fndivide(a: i32, b: i32) ->i32 {
assert!(b != 0, \"Division by zero!\");
a / b
}
fn main() {
// In debug builds, checks are run
// In release builds, checks are removed (unsafe!)
let result = divide(10, 2);
println!(\"Result: {}\", result);
}
Debug vs Release Panics
Debug Mode
letv = vec![1, 2, 3];
letitem = v[99]; // panics
Release Mode
Out-of-bounds access is undefined behavior (Rust still checks in safe code though).
Catching Panics
You can catch panics using catch_unwind:**
use std::panic;
fnmain() {
letresult = panic::catch_unwind(|| {
panic!(\"Oops!\")
});
match result {
Ok(_) => println!(\"No panic\"),
Err(_) => println!(\"Caught a panic!\"),
}
}
fnprocess_number(s: &str) ->Result<i32, String> {
// Use Result for recoverable errors
s.parse::<i32>()
.map_err(|_| String::from(\"Not a valid number\"))
}
fn main() {
// Handle Result properly
match process_number(\"42\") {
Ok(n) => println!(\"Got: {}\", n),
Err(e) => println!(\"Error: {}\", e),
}
// Only use unwrap in examples
let num = process_number(\"99\").unwrap(); // OK for examples
}
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities