3

What's the easiest way to catch an overflow exception in C++?

For example, when I'm writing something like

int a = 10000, b = 100000;
int c = a * b;

or (optionally)

std::cout << a * b;

I'd like to catch an exception (or notification). How to do so? Maybe there is any native solution for GNU C++, isn't there?

Vladyabra
  • 35
  • 1
  • 6

3 Answers3

2

You do the following:

if (b > 0 && a > MAX_REPRESENTABLE_VALUE/b)
{
    throw your_exception("Message");
}

Note that a > MAX_REPRESENTABLE_VALUE/b is equivalent to a*b > MAX_REPRESENTABLE_VALUE mathematically but you have to use the former form if you are doing it with limited-precision arithmetic.

See the header climits for constants for MAX_REPRESENTABLE_VALUE: http://www.cplusplus.com/reference/climits/

juhist
  • 4,210
  • 16
  • 33
  • It's a good solution, but because I can't overload the `operator+` for standart types, it forces me to use own functions, like `add`, `mul`, etc. But it is tiresome and it makes my code too complicated. – Vladyabra Mar 25 '15 at 23:17
  • An alternative would be to create your own type which holds a single `int` and then overload `operator+` for that type. – juhist Mar 26 '15 at 08:17
1

From the standard section 5 Expressions

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

Emphasis mine.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

It's not an exception, it's an error (if that pleases you). The reason is that arithmetic overflow cannot be determined before runtime. It is a runtime error subclassing from superclass error.

What you are looking for is arithmetic overflow.

Check out C++ documentation for overflow_error class here.

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • 4
    What are you getting at? `std::overflow_error` is meant to be thrown, and derives from `std::exception`. Regardless, it does not come into play at all in the OP's situation. – chris Mar 25 '15 at 20:14