rust-cpp icon indicating copy to clipboard operation
rust-cpp copied to clipboard

Add an option for automatically handling exceptions

Open mystor opened this issue 8 years ago • 3 comments

If the C++ code captured throws an exception, it might be nice to have an option for rust-cpp to add an exception handler which translates the exception into a rust panic.

This would have overhead so we may not want it to be the default.

mystor avatar Sep 24 '17 00:09 mystor

I would really love this feature. So instead of this:

    unsafe {
            let mut error_p: *mut i8 = ptr::null_mut();
            cpp!([..., mut error_p as "char*"] {
                try {
                    foo();
                } catch (std::exception& e) {
                    auto what = e.what();
                    error_p = new char[strlen(what)+1];
                    strcpy(error_p, what);
                }
            });
            if !error_p.is_null() {
                let msg = CStr::from_ptr(error_p).to_str().unwrap();
                panic!("{}", msg);
            }
        };

I would get something much simpler.

usamec avatar Nov 17 '17 15:11 usamec

+1 for this feature. Exceptions are not FFI-safe, and should be handled at boundaries. However, some code is guaranteed to be exception-free, e.g. using noexcept C++ attribute.

In spirit of Rust, exception handling wrapper should be opt-out (on be default) instead of opt-in, which brings us to a question of choosing an appropriate syntax for the macro — or add new macro, like cpp_try! or something. Not sure is it would make sense to wrap C++ exceptions in Rust's Result rather than continue unwinding via panic!, but I think that's debatable.

ratijas avatar Jul 07 '21 12:07 ratijas

In spirit of Rust, exception handling wrapper should be opt-out (on be default) instead of opt-in, which brings us to a question of choosing an appropriate syntax for the macro — or add new macro, like cpp_try! or something. Not sure is it would make sense to wrap C++ exceptions in Rust's Result rather than continue unwinding via panic!, but I think that's debatable.

IMHO A Result is more inline than a panic! because a lot of this would be used to write libraries and libraries should not panic!

ahmed-masud avatar Oct 12 '21 19:10 ahmed-masud