Exception handling
Mar 31, 2014 at 11:15pm UTC
OK, it runs at least. I put in proper input and it works great. If I put in a zero, it catches it as my negative number statement. If I put in a w, it also catches it as my negative number statement. I'm sure I'm doing something wrong, can anyone else see it? Thanks in advance!
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
#include <iostream>
using namespace std;
//declare global variables
int feet, inches;
double centimeters;
char ch;
int negNum, badChar;
double convertMeasurements(int f, int i) //function to convert to centimeters
{
double c;
c = ((f * 30.38) + (i * 2.54));
return c;
}
void tryInput() //function to try input
{
try
{
if (feet < -0)
throw negNum;
if (inches < -0)
throw negNum;
if (feet == ch)
throw badChar;
if (inches == ch)
throw badChar;
else cout << "Your values converted to centimeters is: " << convertMeasurements(feet, inches);
}
catch (int negNum)
{
cout << "You entered a negative number for feet or inches! Please re-enter both again as positive numbers: " << endl;
cin.clear();
cin.ignore();
cin >> feet >> inches;
tryInput();
}
catch (int badChar)
{
cout << "You entered a character for feet or inches! Please re-enter both again as positive numbers: " << endl;
cin.clear();
cin.ignore();
cin >> feet >> inches;
tryInput();
}
}
int main()
{
cout << "Please input the length in feet and inches separated by a space. " << endl;
cout << "(example: 1 2, for 1 foot 2 inches): " ;
cin >> feet >> inches;
tryInput();
return 0;
}
Apr 1, 2014 at 12:27am UTC
Never mind, figured it out. Not sure what it was, but it is fixed.
Apr 1, 2014 at 11:22am UTC
You had two catch clauses on the same try block catching exceptions of the same type. The second catch clause would never be executed.
Topic archived. No new replies allowed.