Reputation: 37
I am making a program in C++ that is supposed to calculate the arithmetic results based on the user input. I want to handle it very closely if a user enter a huge value that an int
double
and float
cannot handle then I throw an exception of overflow data. How can I handle these types of exceptions.
The second part is if a user gives me two number and after multiplication or addition, the resulting number might be much bigger than the range of specific data type that how we can handle this type of exception as well?
Upvotes: 1
Views: 228
Reputation: 1771
Beside these answers, you may be interesting in validating the input itself.
In this case you can:
'0'
-'9'
, '+'
, '-'
,
and the decimal-point) These requires a lot of functions and logic to accomplish. I think it is not a trivial task.
Alternatively, you can use <sstream>
header functions to do it for you.
Here is an example code:
#include <iostream>
#include <sstream>
using namespace std;
template <typename T>
bool is_valid_numerical_input(T& num)
{
string str_num;
cout << "\n Enter a number: ";
cin >> str_num;
stringstream sn(str_num);
if (!(sn >> num))
return false;
return true;
}
int main()
{
short number;
if (is_valid_numerical_input(number))
cout << "\n Your number is: " << number;
else
cout << "\n Invalid input";
cout << "\n\n\n";
}
Upvotes: 0
Reputation: 16843
SafeInt library does something like that. It provides template classes that act like regular integers but have checks on all operations for overflow etc. You can read an article on codeguru: Improve Microsoft Visual C++ Application Security and Robustness with SafeInt. It's maintained by microsoft, but it's not windows-only and should most likely be portable.
With SafeInt basically you write regular code and replace int with safeint and all mathematical operations will be automatically checked for overflows. Not sure if there are specializations for doubles though. Perhaps you may take similar idea and write your own wrappers to suite your needs, or you may simply use safeint with 128-bit integers and allocate 64 bits for fractional part and 63 for integer part and have very precise calculations that are always checked.
Upvotes: 1
Reputation: 44284
You can use numeric_limits
to do some checks before doing the arithmetic operation.
For instance a function that adds two int
. You could do something similar to this:
int AddInt(int a, int b)
{
if (a>0 && b>0)
{
// May overflow
if (a > std::numeric_limits<int>::max() - b)
{
// Will overflow
throw ....something....
}
}
else if (a<0 && b<0)
{
// May overflow
if (a < std::numeric_limits<int>::min() + b)
{
// Will overflow
throw ....something....
}
}
// We are good - no overflow
return a+b;
}
Upvotes: 1