[Solved] Try and Catch Int range limit [closed]


I want to catch the error if the value exceeds the maximum int range in c++.

It’s not possible to catch anything, because integer conversion is not specified to throw anything. num will simply have an implementation defined value – or if 123123123123123123123312 is too big to be represented by any integer type on the system, then the program is simply ill-formed.

It is possible that a compiler is smart enough to “catch” this bug and warn you about it. In the case where the integer literal cannot be represented by any integer type, the compiler is required to inform you.

I think integer overflow at runtime is what Im searching.

Integer overflow happens when you do an arithmetic operation (such as add or subtract) on signed integer(s) and the result is not representable by the integer type.

It is not possible to “catch” integer overflow either. When integer overflow happens, the behaviour is undefined. You cannot know whether integer overflow has happened, but you can check whether integer overflow would happen:

int a = getvalue();
int b = getvalue();

bool addWouldOverflow = false; // also check for underflow
if((b < 0) && (a < std::numeric_limits<int>::min() - b))
    addWouldOverflow = true;
else if((b > 0) && (a > std::numeric_limits<int>::max() - b))
    addWouldOverflow = true;

if(addWouldOverflow)
    throw std::overflow_error("Oops! input is bad :(");
else
    return a + b;

solved Try and Catch Int range limit [closed]