capypad
0 Tage Serie
rust / intermediate
Snippet

Panik-Wiederherstellung und unwrap-Variationen

Rust bietet gestaffelte Fehlerbehandlungsstrategien. catch_unwind fängt Paniken zur sanften Wiederherstellung ab. expect bietet klare Fehlermeldungen für Option/Result. unwrap_or bietet Fallback-Werte. get mit Bereich gibt None zurück, anstatt zu paniken, wenn Grenzen ungültig sind.

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");
}
}
Erklärung
1
catch_unwind(AssertUnwindSafe(|| ...))
Führt Closure aus, fängt Panik ab, gibt Result zurück
2
AssertUnwindSafe
Marker-Trait das angibt, dass Closure sicher auspacken kann
3
expect("klare Nachricht")
Entpackt Option/Result, panikt mit eigener Nachricht wenn None/Err
4
unwrap_or(&-1)
Gibt enthaltenen Wert zurück oder bietet Standard wenn None/Err
5
numbers.get(1..5)
Gibt None zurück wenn Bereich Grenzen überschreitet, anstatt zu paniken