Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

catching C++ exceptions not derived from std::exception #284

Closed
astraw opened this issue Sep 5, 2020 · 2 comments
Closed

catching C++ exceptions not derived from std::exception #284

astraw opened this issue Sep 5, 2020 · 2 comments
Labels

Comments

@astraw
Copy link

astraw commented Sep 5, 2020

I'm wrapping a library which throws exceptions not derived from std::exception. It would be nice to take advantage of cxx's automatic C++ try/catch and conversion to a rust Result<T, cxx:Exception>, but it looks like currently only std::exception is caught.

Relatedly, I think it would be useful to have more control over the rust Error type in the automatic conversion. For example, perhaps the user might want to define different error variants which are returned based on runtime behavior.

I don't have specific suggestions for how to deal with these issues, but I wanted to raise them.

@dtolnay
Copy link
Owner

dtolnay commented Sep 5, 2020

This is already supported (but not yet documented; cc #179) by providing a rust::behavior::trycatch function template with the right signature in one of your headers included by the cxx::bridge block. https://github.com/dtolnay/cxx/pull/285/files shows a complete compilable example. I put it as a separate header there in case you would want to reuse the same catch logic in multiple Rust modules, but you could alternatively put the same thing directly in the existing header instead.

#pragma once
#include <string>

namespace rust::behavior {
template <typename Try, typename Fail>
void trycatch(Try &&func, Fail &&fail) noexcept try {
  func();
} catch (int i) {
  auto msg = std::to_string(i);
  fail(msg.c_str());
}
}

@astraw
Copy link
Author

astraw commented Sep 6, 2020

Thank you so much, there's no way I would have found that without your help, despite looking into the code for a while.

The example doesn't quite compile for me. MS C++ compiler tells me error C2429: language feature 'nested-namespace-definition' requires compiler flag '/std:c++17' and fixed this by changing namespace rust::behavior { to namespace rust { namespace behavior {.

@astraw astraw closed this as completed Sep 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants