Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching native C++ exceptions in C#

I have some native C++ class libraries that I have wrapped up in C++ .NET which I then call from C# (three layers!).

I can throw exceptions from C++ .NET and happily catch them in C#. The trouble is that the only way I can catch my native C++ exceptions is by catching System.Exception, which is fine but in the conversion from std::exception to System.Exception I lose the vast majority of the information about the error (for example the error message!). I can catch the native exception in the C++ .NET layer and rethrow as a .NET exception but this is an intrusive solution that requires me to place try-catch blocks (to catch the native exceptions and rethrow) around every C++ .NET method call.

Is there an alternative solution to doing this or am I just going to have to get my hands dirty ...

like image 700
Targett-Adams Avatar asked Aug 14 '12 08:08

Targett-Adams


People also ask

How do you handle exceptions in C?

Use a try block around the statements that might throw exceptions. Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.

Does C language have try-catch?

Yes, it is limited to one try-catch in the same function.

Can we handle exceptions in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.


1 Answers

You are going to have to get your hands dirty, but you can reduce the work a lot by creating a preprocessor macro to encapsulate all the repeated catch logic.

I am assuming you will want to catch several different types of exception, e.g. MFC CException, std::exception, as well as SEH exceptions.

You might also want to write your wrapper functions to return HRESULTS and use SetErrorInfo (i.e. convert to COM error codes and error information) - you may decide this gives a cleaner interface to .Net which can convert this nicely to .Net exceptions. This would avoid the need for a C++.Net layer and allow you to use P/Invoke, as well as making it callable from VBA.

Or you might not... just pointing out the option!

like image 83
Ben Avatar answered Sep 24 '22 15:09

Ben