Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Handle panic! in threads

use std::env;
use std::thread;

// TODO what if the subthread causes a segmentation fault

fn main() {
    println!("Before starting: {:?}", thread::current().id());

    let handle = thread::spawn(|| {
        println!("In thread {:?}", thread::current().id());
        if let Ok(val) = env::var("PANIC") {
            panic!("We have a panic {val}");
        }
        42
    });

    println!("Before join: {:?}", thread::current().id());

    //handle.join().unwrap();
    match handle.join() {
        Ok(val) => println!("The thread returned {val:?}"),
        Err(err) => println!("There was a panic in the thread {err:?}"),
    }

    println!("After ending: {:?}", thread::current().id());
}
cargo run
PANIC=23 cargo run

  • spawn
  • join
  • match