Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for translating exceptions in C++/CLI wrapper class

I am writing a .NET wrapper class for an existing native class which throws exceptions. What are the best practices for translating between native C++ exceptions and Managed exceptions? Catch and re-throw on a one-to-one basis (e.g. std::invalid_argument -> System.System.ArgumentException)? Is there a mapping already drawn up somewhere?

like image 272
Brian Stewart Avatar asked Jan 24 '23 02:01

Brian Stewart


1 Answers

There is no standard mapping that I know of. What I've done in the past is translate the ones I know about, and a catch block for System.Runtime.InteropServices.SEHException. All non-translated exceptions will be turned into that exception. As long as you have a debug build of the code that is throwing the exception, you should get a nice stack trace. Then you can go and look at the exception and write the wrapper.

But on the last project I had to do this on, I went with something much more simple, I ended up writing a couple of System.Exception derivatives for logic_error and runtime_error. Then I would catch those 2 base classes and use typeid(err) to write the .NET message that got thrown. This way I didn't "lose" what was being thrown from the C++ but didn't have to map everything except the most important ones.

like image 161
Justin Rudd Avatar answered Jan 28 '23 15:01

Justin Rudd