My situation is as follows. I am trying to take an input to a program and parse it into an int. I am using atof to do this. However, the user may not have provided an int to the program and I want to catch those exceptions and terminate the program. However, I cannot figure out what kind of exception atof throws and how to store it so as to throw it. I know I need something like the following.
1 2 3 4 5 6 7 8 9
...
std::string input;
try{
int num atof(input.c_str());
}
catch(<exception here>){
cout << "Invalid input" << endl;
exit(0);
}
#include <iostream>
usingnamespace std;
double divide(double a, double b)
{
if (b == 0)
{
throw"Can not divide by zero\n";
}
// This only happens if b != 0
return a / b;
}
int main()
{
double x, y;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
double z;
try
{
z = divide(x, y);
}
catch (constchar *exception)
{
cout << exception;
z = 0; // this line makes the program fix itself enough to run smoothly
}
cout << "z equals: " << z << endl;
return 0;
}
See that exceptions can be thrown more than once and with more than one type:
Here I catch std::exception&, but if you want to be specific, stof() throws std::invalid_argument or std::out_of_range, depending on the kind of error it encounters.
If your compiler is too old for stof(), there's always boost::lexical_cast as already mentioned (it throws boost::bad_lexical_cast, which you can also catch as a std::exception&, or as a std::bad_cast& if you like)