Rust panic
Created By: chatGPT
Panic in Rust is a mechanism for handling unexpected situations during the program's execution. When a panic occurs, the current thread stops executing, and the program begins to unwind the stack, cleaning up resources. This is similar to throwing an exception in other programming languages.
fn main() {
let number = 10;
if number > 5 {
panic!("Number must not be greater than 5!");
}
}
You can trigger a panic using the
panic!
macro, as shown above. If the condition is met (i.e., the number
is greater than 5), the program will stop with an error message. It's crucial to avoid panics in production code, as they may lead to unexpected behavior.fn safe_divide(x: i32, y: i32) -> i32 {
if y == 0 {
panic!("Cannot divide by zero!");
}
x / y
}
fn main() {
let result = safe_divide(10, 0);
}
However, there are ways to recover from a panic using the
std::panic::catch_unwind
function. This allows you to execute code that may panic without terminating the entire program.use std::panic;
fn main() {
let result = panic::catch_unwind(|| {
risky_function();
});
match result {
Ok(_) => println!("Function completed successfully."),
Err(_) => println!("Function panicked!"),
}
}
fn risky_function() {
panic!("Oops! I panicked.");
}
It's advisable to use panic only in situations where recovery is unreasonable, such as during development or when encountering fatal errors that should not happen in a well-defined environment.
fn main() {
let data: Option<i32> = None;
let result = if let Some(value) = data {
value
} else {
panic!("Expected Some value!");
};
println!("Result: {}", result);
}