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

标签 c++ exception refactoring

这是设置。

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

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

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

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

最佳答案

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

If no exception is presently being handled, executing a throw-expression with no operand calls terminate().

因此您的应用程序将终止。这可能不是您想要的。

关于c++ - 如果我使用 "throw;"无异常抛出会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288692/

相关文章:

c++ - C++ 中的编码标准/编码最佳实践

c++ - OpenCV 4.3.0 在 GPU 上计算积分图像>

c++ - 为什么访问这个局部成员变量会引发异常?

c# - 捕获多个自定义FaultException类型

spring-mvc - 在 Spring 中而不是 Servlet 容器中处理 ServletRequestBindingException 等异常

javascript - 是否可以通过将参数传递给函数来将函数中的数据存储到对象文字?

c++ - OpenCV 矩阵创建

java - 拆分临时变量重构示例

c++ - 概括/重构代码

c++ - 如何检查 CSV 文件末尾是否为 '\n'