How to handle exceptions from native code?

放肆的年华 提交于 2021-01-28 21:47:05

问题


Suppose that my application is composed of 3 components. They are:

  1. c++ native library
  2. c++ cli managed library, which wraps native library
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!