【发布时间】:2022-01-16 13:03:12
【问题描述】:
如果两个数字溢出,则不会捕获异常。
输出只打印错误的负数。
Test operator*(const Test &object) const
{
try
{
return Test(value * object.value);
}
catch (std::overflow_error &e)
{
cout << e.what() << endl;
}
catch (std::underflow_error &e)
{
cout << e.what() << endl;
}
}
主要:
Test t1(533222220);
Test t2(300002222);
Test t = t1 * t2; // does not throw exception but t1 * t2 -1416076888
【问题讨论】:
-
什么是价值?请发帖minimal reproducible example。如果 value 是整数类型,则乘法永远不会抛出异常。
-
算术溢出不需要抛出异常。
-
@S.M. — 直到最近,有符号算术溢出导致未定义的行为,因此它可能抛出异常。当然,在实践中,它从来没有这样做过。
-
@PeteBecker 我认为它们仍然未定义,尽管有保证的二进制补码。
标签: c++ exception overflow underflow