Function bitflags::__core::panic::recover
[−]
[src]
pub fn recover<F, R>(f: F) -> Result<R, Box<Any + 'static + Send>> where F: RecoverSafe + FnOnce() -> R
recover
): awaiting feedback
Invokes a closure, capturing the cause of panic if one occurs.
This function will return Ok
with the closure's result if the closure
does not panic, and will return Err(cause)
if the closure panics. The
cause
returned is the object with which panic was originally invoked.
It is currently undefined behavior to unwind from Rust code into foreign code, so this function is particularly useful when Rust is called from another language (normally C). This can run arbitrary Rust code, capturing a panic and allowing a graceful handling of the error.
It is not recommended to use this function for a general try/catch
mechanism. The Result
type is more appropriate to use for functions that
can fail on a regular basis.
The closure provided is required to adhere to the RecoverSafe
to ensure
that all captured variables are safe to cross this recover boundary. The
purpose of this bound is to encode the concept of exception safety in
the type system. Most usage of this function should not need to worry about
this bound as programs are naturally panic safe without unsafe
code. If it
becomes a problem the associated AssertRecoverSafe
wrapper type in this
module can be used to quickly assert that the usage here is indeed exception
safe.
Examples
#![feature(recover, std_panic)] use std::panic; let result = panic::recover(|| { println!("hello!"); }); assert!(result.is_ok()); let result = panic::recover(|| { panic!("oh no!"); }); assert!(result.is_err());