Exception not catching if two numbers are overflowing.
The output only printing the wrong number which is negative.
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;
}
}
In main:
Test t1(533222220);
Test t2(300002222);
Test t = t1 * t2; // does not throw exception but t1 * t2 -1416076888
Despite how it sounds like,
std::overflow_errorandstd::underflow_errordoes not detect arithmetic overflow and underflow by default. In standard library,overflow_erroris only used for convertingbitsetto number, andunderflow_erroris never used. Any other overflow and underflow must be checked manually.For more about how to detect overflows, you might check: How do I detect unsigned integer multiply overflow?