8

I have a C# application which calls a function in a C++ dll. This function can throw various exceptions which inherits std::exception. I currently catch these exceptions like this:

try
{
    //Call to C++ dll
}
catch (System.Exception exception)
{
    //Some error handling code
}

My first question is will this code catch all std::exception? My second question is how can I retrieve the std::exception::what string, if I examine exception.Message I only get "External component has thrown an exception".

EDIT: The function in question is in a non managed C++ dll, and imported like this in the C# class:

[DllImport("SomeDLL.dll")]
public extern static void SomeFunction();
Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • There is a ToString method returns a string representation of the current exception. http://msdn.microsoft.com/en-us/library/system.exception_members.aspx – DumbCoder Aug 20 '10 at 08:15
  • 2
    http://stackoverflow.com/questions/150544/can-you-catch-a-native-exception-in-c-code/150596#150596 – celavek Aug 20 '10 at 08:25

2 Answers2

1

The best way to go would be to handle the exception in C++, and save the error message somewhere. Then, in C# you can check if there was an error message saved, and if it was you can retrieve it.

C++:

try
{
    //do some processing
}
catch(std::exception& ex)
{
    // errorMessage can be a std::string
    errorMessage = ex.what();
}

C#:

[DllImport("SomeDLL.dll")]
public extern static void SomeFunction();
[DllImport("SomeDLL.dll")]
public extern static string GetError();

SomeFunction();
string Error = GetError();
if(String.IsNullOrEmpty(Error)==true)
{
    //The processing was successfull
}
else
{
    //The processing was unsuccessful
    MessageBox.Show(Error);
}
Ove
  • 6,227
  • 2
  • 39
  • 68
  • And what if it is a third party code I have no possibility to modify it? – Tomas Kubes May 03 '16 at 11:52
  • Link against the library in your own C++ wrapper library. – Siddhartha Gandhi May 05 '20 at 23:52
  • This work as well the other way around: catching c# exception from c++ native code. You need to activate SEH exception to work correctly. In the c# wrapper, I save the ex->Message to char * member (using Marshal::StringToHGlobalAnsi) and return with get method. In c++ in "catch(...)" block I read the exception by the get method and throw a std::exception with that message. – Fil May 06 '20 at 13:21
0

Call how? The CLR doesn't really "get" C++ exception handling. If you call the C++ code through COM, add a layer that catches the std::exception and wrap it with a HRESULT/IErrorInfo. If you call it through managed C++, add a layer that wraps it in a managed System.Exception etc.

Mattias S
  • 4,748
  • 2
  • 17
  • 18
  • 1
    The same principle applies to PInvoke. It's easier to find some other protocol for error reporting. Using the return values, output parameters and/or Windows' SetLastError function for example. – Mattias S Aug 20 '10 at 11:13