当我尝试除以 0 时,以下代码未捕获异常。我需要抛出异常,还是计算机在运行时自动抛出异常?
int i = 0;
cin >> i; // what if someone enters zero?
try {
i = 5/i;
}
catch (std::logic_error e) {
cerr << e.what();
}
最佳答案
您需要自己检查并抛出异常。整数除以零在标准 C++ 中也不异常(exception)。
浮点除以零也不是,但至少有特定的处理方法。
ISO 标准中列出的异常(exception)情况是:
namespace std {
class logic_error;
class domain_error;
class invalid_argument;
class length_error;
class out_of_range;
class runtime_error;
class range_error;
class overflow_error;
class underflow_error;
}
您可以非常有说服力地争辩说 overflow_error
(IEEE754 浮点生成的无穷大可能被视为溢出)或 domain_error
(它 是 输入值有问题)将是指示除以零的理想选择。
但是,5.6
部分(C++11
,虽然我认为这与之前的迭代相比没有改变)明确指出:
If the second operand of
/
or%
is zero, the behavior is undefined.
所以,它可能抛出那些(或任何其他)异常。它还可以格式化您的硬盘并 mock :-)
如果你想实现这样的野兽,你可以在下面的程序中使用类似 intDivEx
的东西(使用溢出变体):
#include <iostream>
#include <stdexcept>
// Integer division/remainder, catching divide by zero.
inline int intDivEx (int numerator, int denominator) {
if (denominator == 0)
throw std::overflow_error("Divide by zero exception");
return numerator / denominator;
}
inline int intModEx (int numerator, int denominator) {
if (denominator == 0)
throw std::overflow_error("Divide by zero exception");
return numerator % denominator;
}
int main (void) {
int i = 42;
try { i = intDivEx (10, 0); }
catch (std::overflow_error &e) {
std::cout << e.what() << " -> ";
}
std::cout << i << std::endl;
try { i = intDivEx (10, 2); }
catch (std::overflow_error &e) {
std::cout << e.what() << " -> ";
}
std::cout << i << std::endl;
return 0;
}
这个输出:
Divide by zero exception -> 42
5
你可以看到它抛出并捕获了除以零的异常(保持返回变量不变)。
%
等效项几乎完全相同:
关于c++ - 捕获异常 : divide by zero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6121623/