capypad
0 day streak
rust / intermediate
Snippet

Panic Recovery and unwrap Variations

Rust provides graduated error handling strategies. catch_unwind captures panics for graceful recovery. expect provides clear error messages for Option/Result. unwrap_or offers fallback values. get with range returns None rather than panicking when bounds are invalid.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::panic::{catch_unwind, AssertUnwindSafe};
 
fn risky_operation(divisor: i32) -> i32 {
100 / divisor
}
 
fn main() {
let result = catch_unwind(AssertUnwindSafe(|| {
risky_operation(0)
}));
match result {
Ok(value) => println!("Success: {}", value),
Err(_) => println!("Operation panicked, recovered gracefully"),
}
let numbers = vec![1, 2, 3];
println!("Using expect: {}", numbers.get(0).expect("Vector should have first element"));
println!("Using unwrap_or: {}", numbers.get(5).unwrap_or(&-1));
let maybe_slice = numbers.get(1..5);
if let Some(slice) = maybe_slice {
println!("Slice from index 1: {:?}", slice);
} else {
println!("Slice out of bounds, handled gracefully");
}
}
Breakdown
1
catch_unwind(AssertUnwindSafe(|| ...))
Executes closure, captures any panic, returns Result
2
AssertUnwindSafe
Marker trait indicating closure is safe to unwind across
3
expect("clear message")
Unwraps Option/Result, panics with custom message if None/Err
4
unwrap_or(&-1)
Returns contained value or provides default if None/Err
5
numbers.get(1..5)
Returns None when range exceeds bounds instead of panicking