这个警告在C++中对于异常处理意味着什么?

我为除法运算编写了一个异常处理代码:
我包含了Zero division error, Negative value error(不是异常,但我包含了它!)和Indeterminate form error(我也包含了它)。

然后在编译后它显示一些警告,但.exe文件按预期运行。
这是我在编译后收到的代码和输出。

代码

#include <iostream>
#include <stdexcept>

using namespace std;

int main(void)
{
    int numerator, denominator, quotient, remainder;
    cout << "Enter the value of numerator and denominator: ";
    cin >> numerator >> denominator;
    try
    {
        if (!numerator && !denominator)
        {
            throw logic_error("Logical Error: Indeterminate Form!n");
        }
        else if (!denominator)
        {
            throw runtime_error("Math Error: Attemp to divide by zero!n");
        }

        else if (numerator < 0 || denominator < 0)
        {
            throw invalid_argument("Invalid Arguments: Negative numbers not allowed!n");
        }
        else
        {
            quotient = numerator / denominator;
            remainder = numerator % denominator;
            cout << "The result after division is:n"
                 << "Quotient: " << quotient << "nRemainder: " << remainder << 'n';
        }
    }
    catch (logic_error &exc)
    {
        cout << exc.what();
    }
    catch (runtime_error &exc)
    {
        cout << exc.what();
    }
    catch (invalid_argument &exc)
    {
        cout << exc.what();
    }
    catch (...)
    {
        cout << "Some Exception Occured!n";
    }

    cout << "nProgram Finished...n";
    return 0;
}

输出

Exceptional_Handling_05.cpp: In function 'int main()':
Exceptional_Handling_05.cpp:42:5: warning: exception of type 'std::invalid_argument' will be caught
   42 |     catch (invalid_argument &exc)
      |     ^~~~~
Exceptional_Handling_05.cpp:34:5: warning:    by earlier handler for 'std::logic_error'
   34 |     catch (logic_error &exc)
      |     ^~~~~
Enter the value of numerator and denominator: 52 0
Math Error: Attemp to divide by zero!

Program Finished...

这个警告在这里是什么意思?
尽管程序的输出在每个角落和特殊情况下都符合预期。

回答

触发相同警告的代码的精简版本是这样的:

#include <iostream>
#include <stdexcept>

int main()
{
    int numerator = -1, denominator = -1;
    try
    {        
        if (numerator < 0 || denominator < 0)
        {
            throw std::invalid_argument("Invalid Arguments: Negative numbers not allowed!n");
        }
    }
    catch (std::logic_error &exc)
    {
        std::cout << exc.what();
    }
    catch (std::invalid_argument &exc)
    {
        std::cout << " THIS IS NEVER REACHED !!";
        std::cout << exc.what();
    }
}

输出是

Invalid Arguments: Negative numbers not allowed!

因为std::invalid_argument继承自std::logic_error并且异常已经由第一个catch. 如果你想分别捕获一般的logic_error和更专业的invalid_argument,你需要按照相反的顺序进行:

catch (std::invalid_argument &exc)
{
    std::cout << exc.what();
}
catch (std::logic_error &exc)
{
    std::cout << exc.what();
}


以上是这个警告在C++中对于异常处理意味着什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>