Best practice for translating exceptions to C ++ / CLI shell class

I am writing a .NET wrapper class for an existing native class that throws exceptions. What are the best translation methods between C ++ source exceptions and managed exceptions? Catch and re-throw on a one-to-one basis (for example, std :: invalid_argument โ†’ System.System.ArgumentException)? Is there any kind of mapping somewhere?

+4
source share
4 answers

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

But in the last project I had to do this, I went with something much simpler, in the end I wrote a couple of System.Exception derivatives for logic_error and runtime_error. Then I would catch these 2 base classes and use typeid (err) to write the .NET message that was thrown. Thus, I did not "lose" what was thrown from C ++, but I did not need to display everything except the most important ones.

+4
source

Individual matching seems to me the most appropriate approach. A โ€œuniversalโ€ mapping is hardly possible due to application-specific exceptions, although there is some obvious mapping for STL exception classes.

There is also a problem of SEH exceptions from unmanaged code. Depending on your situation, you may also need to catch and wrap them.

+2
source

I think it depends on the design of the wrapper. If the manager wrapper interface is almost identical to the unmanaged library interface, then reverse the 1: 1 exceptions. If you change the interface significantly, throw exceptions that are most suitable for the new interface. In any case, make sure that the wrapper throws exceptions at any time when the operation cannot be performed so that it complies with .NET development guidelines.

+2
source

What are you really trying to do?

Interop is already translating its own exceptions into managed ones, including SEH exceptions. However, good design requires ALL exceptions to be caught at the API level. You should not deviate from this unless there is a good reason. We do not know enough about your design.

+1
source

Source: https://habr.com/ru/post/1277045/


All Articles