问题
Suppose that my application is composed of 3 components. They are:
- c++ native library
- c++ cli managed library, which wraps native library
- c# gui application.
As I understand, any native exception, thrown from a native c++ library will be wrapped with SEHException managed class. I am interested in the next steps, what is recommended to do after the creation of such an exception object.
Should I catch all such possible exceptions within the c++ cli managed library then create an appropriate managed exception? Something like this:
void some_managed_action()
{
try
{
native_object->some_native_action();
}
catch (const NativeException& e)
{
// What should I do with exception e and native object? before throwing new managed exception
// Will SEH wrapper automatically delete native exception object
// delete all native objects?
throw gcnew ManagedException(get_message(e));
}
}
Maybe there are some pitfalls in such an approach? Thanks for any advice.
回答1:
Use
try
{
}
catch (Exception ex)
{
// .NET exception
}
catch
{
// native exception
}
A catch block that handles Exception catches all Common Language Specification (CLS) compliant exceptions. However, it does not catch non-CLS compliant exceptions. Non-CLS compliant exceptions can be thrown from native code or from managed code that was generated by the Microsoft intermediate language (MSIL) Assembler. Notice that the C# and Visual Basic compilers do not allow non-CLS compliant exceptions to be thrown and Visual Basic does not catch non-CLS compliant exceptions. If the intent of the catch block is to handle all exceptions, use the following general catch block syntax.
C#: catch {}
CA2102: Catch non-CLSCompliant exceptions in general handlers
来源:https://stackoverflow.com/questions/40468923/how-to-handle-exceptions-from-native-code