rust - Recovering from `panic!` in another thread -
i know in rust there no try/catch, , can't throw rolling save thread panicking.
i know should not create , handle errors this. example's sake.
however, wondering best way recover panic is. have now:
use std::thread; fn main() { println!("hello, world!"); let h = thread::spawn(|| { thread::sleep_ms(1000); panic!("boom"); }); let r = h.join(); match r { ok(r) => println!("all well! {:?}", r), err(e) => println!("got error! {:?}", e) } println!("exiting main!"); }
is there better way handle errors other threads? there way capture message of panic? seems tell me error of type any
. thanks!
putting aside "you should using result
possible," yes, how catch panic in rust. keep in mind "recover" perhaps not best way of phrasing in rust. don't recover panics in rust, isolate them, detect them. there no on error resume next
:p.
that said, there 2 things add example. first how @ panic message. key observation any
, in order used, must explicitly downcast exact, concrete type contains. in case, since panic message &'static str
, need downcast that.
the second thing there new api in nightly called catch_panic
lets isolate panic without having start thread. said, comes same restrictions spawning new thread: cannot pass non-'static
reference across isolation boundary. note unstable addition; there no guarantees stability yet, , you'll need nightly compiler access it.
here example shows both of those. can run on rust playpen.
#![feature(catch_panic)] use std::thread; fn main() { println!("hello, world!"); let h = thread::spawn(|| { thread::sleep_ms(500); panic!("boom"); }); let r = h.join(); handle(r); let r = thread::catch_panic(|| { thread::sleep_ms(500); panic!(string::from("boom again!")); }); handle(r); println!("exiting main!"); } fn handle(r: thread::result<()>) { match r { ok(r) => println!("all well! {:?}", r), err(e) => { if let some(e) = e.downcast_ref::<&'static str>() { println!("got error: {}", e); } else { println!("got unknown error: {:?}", e); } } } }
Comments
Post a Comment