This code snippet will allow your application to set a custom panic and allocation error hook.
It's useful for games and GUIs, as it allows you to show a user-friendly error no matter what happens to your program.
#![feature(alloc_error_hook)]
fn set_hooks() {
// Set the allocation error hook to panic
// Usually it will abort the program, which means no unwinding or panic handling can be done
std::alloc::set_alloc_error_hook(|layout: std::alloc::Layout| {
panic!("memory allocation of {} bytes failed", layout.size());
});
// Gets the default panic hook, so after
// the custom one has run you can still get a backtrace
let ph = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo| {
// Put custom panic handling here
// e.g. popup window
println!("{:?}", info);
ph(info);
}));
}
/// Set the allocation and panic hook back to default
fn unset_hooks() {
std::alloc::take_alloc_error_hook();
let _ = std::panic::take_hook();
}
fn main() {
set_hooks();
let _: Vec<u8> = vec![0; 1_000_000_000_000];
// This code will never be run in this example because it panics
// You can use this in your code if you want to unset your custom hooks
unset_hooks();
}