Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a panic?

Tags:

rust

I need to catch a panic so that it doesn't exit the the program. For example, how to catch a panic here and print "Hello, World"?:

fn main() {
    let v = vec![1, 2, 3];

    v[99];
    println!("Hello, World");
}
like image 888
fish0fqwerty Avatar asked Sep 14 '25 20:09

fish0fqwerty


1 Answers

You can use std::panic::catch_unwind to, well, catch unwinding panics, but do make sure to read the documentation first:

fn main() {
    let v = vec![1, 2, 3];
    let panics = std::panic::catch_unwind(|| v[99]).is_err();
    assert!(panics);
    println!("Hello, World");
}
like image 123
isaactfa Avatar answered Sep 17 '25 10:09

isaactfa