Problem with Exception thrown due to Overflow of number

Ok I am making a program which will display the sum of all the indexes of an array. However, if the sum exceeds the max value of int or goes below the minimum value, it will give an error, through Exception Handling.
So, I made the program but it is not working and the program isn't giving error..
Can anyone explain the reason, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;
int sum(int *, int);
int main()
{
	int *arr;
	cout << "Enter Size of Array: "; 
	int s; 
	cin >> s; 
	arr = new int[s];
	cout << "Enter Values for Array: "; 
	for (int i = 0; i < s; i++)
		cin >> arr[i]; 
	if (sum(arr, s) != 0)
		cout << sum(arr, s);
	cout << endl; 
	system("pause");
	return 0; 

}
int sum(int *arr, int x)
{
	int s = 0;
	try {
		for (int i = 0; i < x; i++)
		{
			s = s + arr[i];
		}
	}
	catch (const string& what_arg)
	{
		cout << "Overflow/Underflow Error!\n"; 
		return 0;
	}
	return s; 
}


Here's the output I am getting,

1
2
3
4
Enter Size of Array: 2
Enter Values for Array: 2147483647 5
-2147483644
Press any key to continue . . .
However, if the sum exceeds the max value of int or goes below the minimum value, it will give an error, through Exception Handling


Why would it do that?

There's no C++ exception thrown for that. There's usually no hardware exception, either. It's up to you to detect it. In assembly language you can use the status flags to detect it. In C++ it's a little more involved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <limits>

int sum(int*, int);

int main()
{
    std::cout << "Enter Size of Array: "; 
    int n; 
    std::cin >> n;
    int* arr = new int[n];

    std::cout << "Enter Values for Array: "; 
    for (int i = 0; i < n; i++)
        std::cin >> arr[i];

    if (!std::cin)
        std::cerr << "Bad numeric input\n";
    else
        std::cout << sum(arr, n) << '\n';
}

int sum(int *arr, int n)
{
    const int Min = std::numeric_limits<int>::min(),
              Max = std::numeric_limits<int>::max();
    int s = 0;
    for (int i = 0; i < n; i++) {
        if (s < 0) {
            if (arr[i] < 0 && Min - arr[i] > s) {
                std::cerr << "Underflow error\n";
                return 0;
            }
        }
        else if (s > 0) {
            if (arr[i] > 0 && Max - arr[i] < s) {
                std::cerr << "Overflow error\n";
                return 0;
            }
        }
        s += arr[i];
    }
    return s; 
}

Last edited on
The problem is supposed to be done with the use of Exception Handling...

Now, even if I simply place a check on the cin (that a number bigger than MAX INT should give an exception, it still isn't giving it) :/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;
int sum(int *, int);
int main()
{
	int *arr;
	cout << "Enter Size of Array: ";
	int s;
	cin >> s;
	arr = new int[s];
	cout << "Enter Values for Array: ";
	cout << sum(arr, s);
	cout << endl;
	system("pause");
	return 0;

}
int sum(int *arr, int x)
{
	int s = 0; 
	try 
	{
		for (int i = 0; i < x; i++)
		{
			cin >> arr[i];
			if (arr[i] > INT_MAX)
				throw 0; 
			if (arr[i] < INT_MIN)
				throw 0; 
		}
		for (int i = 0; i < x; i++)
		{
			s = s + arr[i];
		}
	}
	catch (int)
	{
		cout << "Overflow/Underflow Error!\n";
		return 0;
	}
	return s;
}
Last edited on
What number could possible ever be in arr[i] that is bigger than INT_MAX?

Name one. Tell us a number that could be in arr[i] that is bigger than INT_MAX.

Remember, arr[i] is an int, so what is the biggest number that could be there?
Last edited on
You are right
But then how can I possibly detect an error if a number bigger than INT MAX is inputted by the user by using Exception Handling?
> how can I possibly detect an error if a number bigger than INT MAX is inputted by the user
> by using Exception Handling?

We can set an exception mask for the stream; the stream will then throw an exception on failure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <stdexcept>
#include <vector>

int checked_get_int()
{
    const auto old_mask = std::cin.exceptions() ;

    // ask std::cin to throw an exception on failure
    // https://en.cppreference.com/w/cpp/io/basic_ios/exceptions
    std::cin.exceptions( std::cin.failbit|std::cin.eofbit|std::cin.badbit ) ;

    int number = 0 ;
    try
    {
        std::cin >> number ;
        std::cin.exceptions(old_mask) ;
        return number ;
    }

    catch( const std::ios_base::failure& )
    {
        std::cin.exceptions(old_mask) ;

        // the number entered is too large to be held in an int
        if( number == std::numeric_limits<int>::max() )
            throw std::out_of_range( "integer overflow: that number is too large" ) ;

        // the number entered is too small to be held in an int
        else if( number == std::numeric_limits<int>::min() )
            throw std::out_of_range( "integer overflow: that number is too small" ) ;

        // some other input error (eg. non-numeric input, say 'abcd').
        else throw ; // rethrow the exception
    }
}

int main()
{
    std::cout << "enter size of array: " ;
    std::size_t sz ;
    std::cin >> sz ;

    // create an array (vector) containing sz elements
    // https://cal-linux.com/tutorials/vectors.html
    std::vector<int> array(sz) ; // this may throw if sz is monstrously large

    std::cout << "enter " << sz << " values for the array\n" ;

    try
    {
        // range based loop: http://www.stroustrup.com/C++11FAQ.html#for
        for( int& v : array ) v = checked_get_int() ;
    }

    catch( const std::out_of_range& e ) // number entered is too large / too smallk
    {
        std::cout << "error - value entered is out of range : " << e.what() << '\n' ;
        return 1 ;
    }

    catch( const std::exception& e ) // some other input error
    {
        std::cout << "input error : " << e.what() << '\n' ;
        return 1 ;
    }

    std::cout << sz << " values were entered successfully\n" ;
}
Topic archived. No new replies allowed.