【问题标题】:What is the order of catch block execution when multiple exceptions are thrown and why? [closed]抛出多个异常时,catch 块执行的顺序是什么,为什么? [关闭]
【发布时间】:2019-08-09 06:21:04
【问题描述】:

在下面的代码中,函数在一个语句中抛出两个异常。现在,为什么 int catch 块处理异常而不是另一个块? 是否总是最后一个异常被处理?


    try
    {
        quotient = safe_divide(numerator , denominator);
    }
    catch(DivideByZero)
    {
        cout << "Error: Division by zero!\n"
            << "Program aborting.\n";
        system("pause");
    }

    catch (int )
    {
        cout << "got you " << endl;
        cout << "top : " << numerator << endl;

        system("Pause");
        exit(0);
    }

    double safe_divide(int top, int bottom) throw(DivideByZero,int)
    {
        if(bottom == 0)
            throw (DivideByZero(),top);

        return top/static_cast<double>(bottom);
    }


【问题讨论】:

  • 在下面的代码中,函数在一个语句中抛出了两个异常。 - 它没有,只有top被抛出,而DivideByZero()的结果被丢弃,因为到逗号运算符
  • 你的意思是像throw DivideByZero(top); 这样的东西吗?

标签: c++ exception try-catch throw


【解决方案1】:

这个表达式throw (DivideByZero(),top); 不会抛出两个异常(这是不可能的)。它只抛出一个异常,即int

这里的, 是一个很少使用的逗号运算符的例子。该运算符接受两个表达式,计算第一个,丢弃结果,然后计算第二个并返回它的值。

实际上,逗号运算符仅在第一个表达式有一些副作用时使用。由于这里不是这种情况,因此您的代码可以简化为 throw top;,这清楚地表明正在抛出 int

【讨论】:

  • 关于使用-Wall 的评论会改进这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2013-09-16
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
相关资源
最近更新 更多