如何处理本机代码中的异常? [英] How to handle exceptions from native code?

查看:72
本文介绍了如何处理本机代码中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的应用程序由3个组件组成.他们是:

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

  1. c ++本机库
  2. c ++ cli托管库,其中包装了本机库
  3. c#gui应用程序.

据我了解,从本机c ++库引发的任何本机异常都将被SEHException托管类包装.我对接下来的步骤感兴趣,建议在创建此类异常对象之后执行哪些操作.

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.

我应该在c ++ cli托管库中捕获所有此类可能的异常,然后创建适当的托管异常吗?像这样:

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.

推荐答案

使用

try 
{
} 
catch (Exception ex) 
{
    // .NET exception
} 
catch 
{
    // native exception
}

处理异常的catch块捕获所有公共语言符合规范(CLS)的异常.但是,它没有赶上不符合CLS的例外.不符合CLS的异常可以是从本机代码或托管代码生成的托管代码抛出Microsoft中间语言(MSIL)汇编程序.请注意,C#和Visual Basic编译器不允许使用不符合CLS的异常将被抛出并且Visual Basic无法捕获不符合CLS的要求例外情况.如果catch块的意图是处理所有例外,请使用以下常规catch块语法.

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#:抓住{}

CA2102:在常规处理程序中捕获非CLS兼容异常

这篇关于如何处理本机代码中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆