引发多个异常时catch块执行的顺序是什么?为什么?

时间:2019-08-09 06:21:04

标签: c++ exception try-catch throw

在以下代码中,该函数在一条语句中引发两个异常。现在,为什么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);
    }


1 个答案:

答案 0 :(得分:7)

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

此处,是很少使用的逗号运算符的一个示例。该运算符采用两个表达式,对第一个表达式求值,将结果扔掉,然后对第二个表达式求值并返回该值。

实际上,逗号运算符仅在第一个表达式有副作用时使用。既然不是这种情况,可以将您的代码简化为throw top;,这很清楚地抛出了int