异常处理中的代码重用 [英] Code reuse in exception handling

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

问题描述

我正在为C ++编写的一些功能开发一个C api,我想确保没有异常从任何导出的C函数中传播。



简单的方法是确保每个导出的函数都包含在一个:

  try {
//做实际代码
} catch(...){
return ERROR_UNHANDLED_EXCEPTION;
}

我知道一个例外,经常错过C ++代码是std :: bad_alloc我想特别对待它,我会写这样的东西,而不是:

  try {
/ /运行实际代码
} catch(std :: bad_alloc& e){
return ERROR_BAD_ALLOC;
} catch(...){
return ERROR_UNHANDLED_EXCEPTION;
}

有可能以一些聪明的方式分解这个,以便我可以全球治疗在每个导出的函数周围添加一个异常处理程序的新的catch语句时,会出现一些错误?



我知道这可以解决使用预处理器,但之前

解决方案

您只能使用一个处理程序对于所有可能的异常,并从每个或您的API实现函数中调用它,如下所示:

  int HandleException()
{
try
{
throw;
}

// TODO:添加更多类型的异常

catch(std :: bad_alloc&)
{
return ERROR_BAD_ALLOC ;
}
catch(...)
{
return ERROR_UNHANDLED_EXCEPTION;
}
}

在每个导出的函数中:

  try 
{
...
}
catch(...)
{
return HandleException();
}


I'm developing a C api for some functionality written in C++ and I want to make sure that no exceptions are propagated out of any of the exported C functions.

The simple way to do it is making sure each exported function is contained in a:

try {
   // Do the actual code
} catch (...) {
   return ERROR_UNHANDLED_EXCEPTION;
}

Let's say I know one exception that is often missed inside the C++ code is std::bad_alloc and I want to treat it specially I'd write something like this instead:

try {
   // Run the actual code
} catch (std::bad_alloc& e) {
   return ERROR_BAD_ALLOC;
} catch (...) {
   return ERROR_UNHANDLED_EXCEPTION;
}

Is it possible to decompose this in some clever way so that I can globally treat some errors differently without adding a new catch statement for the exception handler around every exported function?

I'm aware of that this is possible to solve using the preprocessor, but before going down that road, I'd make sure there is no other way to do it.

解决方案

You can use only one handler function for all possible exceptions, and call it from each or your API implementation functions, as below:

int HandleException()
{
    try 
    {
        throw;
    }

    // TODO: add more types of exceptions

    catch( std::bad_alloc & ) 
    {
       return ERROR_BAD_ALLOC;
    }
    catch( ... )
    {
        return ERROR_UNHANDLED_EXCEPTION;
    }
}

And in each exported function:

try
{
    ...
}
catch( ... )
{
    return HandleException();
}

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

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