如果我使用"throw"会发生什么?无异常抛出?

dew*_*rde 9 c++ refactoring exception

这是设置.

我有一个C++程序调用几个函数,所有这些函数都可能抛出相同的异常集,并且我希望每个函数中的异常具有相同的行为(例如,打印错误消息并将所有数据重置为exceptionA的默认值;只需打印对于exceptionB;干净地关闭所有其他异常).

似乎我应该能够设置catch行为来调用私有函数,它只是重新抛出错误,并执行捕获,如下所示:

void aFunction()
{
    try{ /* do some stuff that might throw */ }
    catch(...){handle();}
}

void bFunction()
{
    try{ /* do some stuff that might throw */ }
    catch(...){handle();}
}

void handle()
{
    try{throw;}
    catch(anException)
    {
        // common code for both aFunction and bFunction
        // involving the exception they threw
    }
    catch(anotherException)
    {
        // common code for both aFunction and bFunction
        // involving the exception they threw
    }
    catch(...)
    {
        // common code for both aFunction and bFunction
        // involving the exception they threw
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果在异常类之外调用"handle"会发生什么.我知道这应该永远不会发生,但我想知道C++标准是否未定义该行为.

Joh*_*lla 16

如果handle()在异常的上下文之外调用,则throw不会处理异常.在这种情况下,标准(参见第15.5.1节)规定了

如果当前没有处理异常,则执行a throw-expression不带操作数调用terminate().

所以你的申请将会终止.这可能不是你想要的.


Bri*_*ndy 5

如果在catch块中使用throw,它将重新抛出异常.如果在catch块之外使用throw,它将终止应用程序.