Can You Catch a Native Exception in C# Code

Can you catch a native exception in C# code?

You can use Win32Exception and use its NativeErrorCode property to handle it appropriately.

// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155;

void OpenFile(string filePath)
{
Process process = new Process();

try
{
// Calls native application registered for the file type
// This may throw native exception
process.StartInfo.FileName = filePath;
process.StartInfo.Verb = "Open";
process.StartInfo.CreateNoWindow = true;
process.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||
e.NativeErrorCode == ERROR_ACCESS_DENIED ||
e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
{
MessageBox.Show(this, e.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}

catch native exception in dotnet core

I set-up this Minimal, Complete and Verifiable example that demonstrates how native exceptions are NOT caught whatsoever by managed C# .NET Core code, on Linux.

As described in the issue I opened for dotnet/coreclr, I've tried (m)any possible weapon(s) in the arsenal, to no avail.

The direct answer given by dotnet team was:

We do not support exception handling interop on Unix. There is no good way to do it. The Mono project has a great write up on it here: http://www.mono-project.com/docs/advanced/pinvoke/#runtime-exception-propagation . The same reasoning applies to .NET Core.

The Mono project's solution, which is also recommended by the dotnet team, is:

C++ exceptions will need to be mapped into an “out” parameter or a return value, so that managed code can know what error occurred, and (optionally) throw a managed exception to “propagate” the original C++ exception.

That's what we eneded up implementing and, well, it works :).

Capturing native exception from c# and getting the exception.what() after it leaves scope

You could allocate a char-buffer (within the native DLL) for your "errorText"-Parameter and copy the text "ex.what()" to that buffer. In that case, the Memory will stay valid.
But I think, you will have to release the char-buffer by your own after you read the string in C# to prevent a memory-leak.



Related Topics



Leave a reply



Submit