0

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
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
n9p4
  • 304
  • 8
  • 34

3 Answers3

3

Exception not catching if two numbers are overflowing.

Correct. No exceptions are thrown by integer arithmetic. If signed integer operation overflows, then the behaviour of the program is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

Despite how it sounds like, std::overflow_error and std::underflow_error does not detect arithmetic overflow and underflow by default. In standard library, overflow_error is only used for converting bitset to number, and underflow_error is 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?

Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39
1

In standard C++, catch blocks only work with throw statements, and there are no throw statements in the code you have shown.

Some compilers have vendor extensions that may convert non-exception errors, like integer overflows, into C++ exceptions, but your example is clearly not a case of that happening.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770