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?
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.
#include <iostream>
#include <stdexcept>
#include <vector>
int checked_get_int()
{
constauto 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
elseif( 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').
elsethrow ; // 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#forfor( 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" ;
}