Las*_*lan 15 c c++ exception-handling
我正在为用C++编写的一些功能开发一个C api,我想确保没有任何异常从任何导出的C函数中传播出来.
这样做的简单方法是确保每个导出的函数都包含在:
try {
// Do the actual code
} catch (...) {
return ERROR_UNHANDLED_EXCEPTION;
}
Run Code Online (Sandbox Code Playgroud)
假设我知道在C++代码中经常遗漏的一个异常是std :: bad_alloc,我想特别对待它我会写这样的东西:
try {
// Run the actual code
} catch (std::bad_alloc& e) {
return ERROR_BAD_ALLOC;
} catch (...) {
return ERROR_UNHANDLED_EXCEPTION;
}
Run Code Online (Sandbox Code Playgroud)
是否有可能以一种巧妙的方式对其进行分解,以便我能够以不同的方式全局处理某些错误而无需为每个导出函数添加新的catch语句用于异常处理程序?
我知道使用预处理器可以解决这个问题,但在走这条路之前,我确保没有其他方法可以做到这一点.
Jem*_*Jem 28
对于所有可能的异常,您只能使用一个处理函数,并从每个或您的API实现函数中调用它,如下所示:
int HandleException()
{
try
{
throw;
}
// TODO: add more types of exceptions
catch( std::bad_alloc & )
{
return ERROR_BAD_ALLOC;
}
catch( ... )
{
return ERROR_UNHANDLED_EXCEPTION;
}
}
Run Code Online (Sandbox Code Playgroud)
并在每个导出的功能:
try
{
...
}
catch( ... )
{
return HandleException();
}
Run Code Online (Sandbox Code Playgroud)