0

I want to check under what circumstance will overflow_error and underflow_error exception be generated in c++, so I wrote a demo to try to generate overflow_error exception, but failed:

#include <iostream>
#include <stdexcept>
using std::cout; using std::endl;
int main() {
    try {
        int a = std::pow(2, 31) - 1;
        cout << a << endl;
        int b = 1;
        int c = a + b;
        cout << c << endl;
    } catch (std::overflow_error ex) {
        cout << ex.what() << endl;
    }
    return 0;
}

The out put is:

2147483647
-2147483648

As you can see, no overflow_error exception generated, so, my questions are what the arithmetic overflow errors and arithmetic underflow errors are and how to generate overflow_error and underflow_error exception in c++?

cong
  • 1,105
  • 1
  • 12
  • 29
  • 1
    Possible duplicate of [Is overflow\_error caught at runtime in C++ when a integer variable cannot hold a value that it is not supposed to](https://stackoverflow.com/questions/35138864/is-overflow-error-caught-at-runtime-in-c-when-a-integer-variable-cannot-hold-a) – user202729 Mar 19 '18 at 05:05
  • 1
    Which unfortunately didn't cover the `underflow_error`. – user202729 Mar 19 '18 at 05:08
  • Why don't you post an answer so that I can mark it favorite? – cong Mar 19 '18 at 05:16

1 Answers1

2

The only standard library components that throw std::overflow_error are std::bitset::to_ulong and std::bitset::to_ullong.

The standard library components do not throw std::underflow_error (mathematical functions report underflow errors as specified in math_errhandling).

In your example, you are trying to check signed integer overflow. You need to specify flag for this check.

For example:

Use clang++ to compile and link your program with -fsanitize=undefined flag.

% cat test.cc
int main(int argc, char **argv) {
  int k = 0x7fffffff;
  k += argc;
  return 0;
}
% clang++ -fsanitize=undefined test.cc
% ./a.out

test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

Smit Ycyken
  • 1,189
  • 1
  • 11
  • 25