Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#![feature(rt)]
#![feature(unmarked_api)]
use std::thread;
use std::any::Any;
use std::rt::unwind::set_panic_handler;
fn main() {
// Use the default handler
panic!("Something's wrong"); // Prints "thread '<main>' panicked at 'Something's wrong', /Users/yohai/code/panic_handlers_test.rs:10"
// Or... (comment out the code above)
set_panic_handler(simple_handler);
panic!("Something's wrong"); // Prints "A thread panicked: Something's wrong"
//
// Or... (comment out the code above)
set_panic_handler(silent_handler);
panic!("Something's wrong (but you'll never see this message)"); // Prints nothing
}
fn silent_handler(_msg: &(Any + Send), _file: &'static str, _line: u32) {}
fn simple_handler(obj: &(Any + Send), _file: &'static str, _line: u32) {
let msg = match obj.downcast_ref::<&'static str>() {
Some(s) => *s,
None => match obj.downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
}
};
println!("A thread panicked: {}", &*msg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment