C++ Error Handling

  1. #[cxx::bridge]
  2. mod ffi {
  3. unsafe extern "C++" {
  4. include!("example/include/example.h");
  5. fn fallible(depth: usize) -> Result<String>;
  6. }
  7. }
  8. fn main() {
  9. if let Err(err) = ffi::fallible(99) {
  10. eprintln!("Error: {}", err);
  11. process::exit(1);
  12. }
  13. }
  • C++ functions declared to return a Result will catch any thrown exception on the C++ side and return it as an Err value to the calling Rust function.
  • If an exception is thrown from an extern “C++” function that is not declared by the CXX bridge to return Result, the program calls C++’s std::terminate. The behavior is equivalent to the same exception being thrown through a noexcept C++ function.