【发布时间】:2021-09-30 08:36:44
【问题描述】:
我写了除法运算的异常处理代码:
我包含了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...
这个警告在这里意味着什么?
尽管程序的输出在每个角落和例外情况下都符合预期。
【问题讨论】:
-
错误信息其实很清楚。
invalid_argument不需要 catch,因为它继承自logic_error,因此已经被捕获。在catch (invalid_argument &exc)里面加一些std::cout或者类似的,看看就不会触发了 -
顺便说一句,尽量少用异常,用于异常情况,而不是控制流。用户输入错误的输入并不是那么特殊。您也可以在检查条件的地方打印消息。但是,我想这是一个关于异常的练习,因此删除它们将毫无意义
-
@463035818_is_not_a_number 是的,我现在正在学习 C++ 中的异常处理。这不是应该做的程序,我只是在练习。
-
顺便说一句,它不称为“异常处理”
-
哦,好的,感谢您的编辑 :-)