Updated for Rust 1.10+, see revision history for the previous version of the answer
很好的一点是,在go中,主线程没有被解开,程序只是崩溃了,但是最初的panic 被报告了.事实上,这就是我想要的行为(尽管理想情况下,各地的资源都会得到适当清理).
这可以通过最近稳定的std::panic::set_hook()
功能实现.有了它,你可以设置一个钩子来打印panic 信息,然后退出整个过程,比如:
use std::thread;
use std::panic;
use std::process;
fn main() {
// take_hook() returns the default hook in case when a custom one is not set
let orig_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
process::exit(1);
}));
thread::spawn(move || {
panic!("something bad happened");
}).join();
// this line won't ever be invoked because of process::exit()
println!("Won't be printed");
}
try 注释set_hook()
调用,你会看到println!()
行被执行.
然而,由于使用了process::exit()
,这种方法将不允许释放由其他线程分配的资源.事实上,我不确定Go运行时是否也允许这样做;它很可能使用相同的方法中止该过程.