在异常处理code重用

在异常处理code重用

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

问题描述

我在开发C ++编写的一些功能的C API,我想确保没有异常繁殖出任何导出的C函数。

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;
}

比方说,我知道有一个例外,往往是错过了C ​​++ code里面则为std :: bad_alloc,我希望把它特意我会写这样的事情,而不是:

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;
}

是否有可能以某种巧妙的方式分解,这样我可以在全球不同的方式对待一些错误,而周围的每一个导出函数添加一个新的catch语句的异常处理程序?

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?

我所知道的,这是可能使用preprocessor,但在此之前走这条路,我会确保没有其他办法做到这一点来解决。

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.

推荐答案

您可以按照以下只用一个处理函数为所有可能的异常,并从每个或您的API实现的功能调用它,

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;
    }
}

和每个导出函数:

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

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

08-24 02:59