-
Catch the exception
How can I catch a exception were I'm expecting an integer but the user enters a real or string.
Can someone give me a list of the basic exceptions that can be caught?
I know the format of catching them is as follows, but what do you put in the parenthesis of the catch bit, in Java you code something like catch(NumberFormatException exp) to catch number entry errors etc.
Code:
try
{
// statements
}
catch()
{
// statements
}
Bellow is a small test piece of the project I'm doing and I wish to catch an exception when the users entry is taken at the 'cin' bit.
Code:
int menu()
{
int selectedOption = 0;
do
{
clearScreen();
cout << "MAIN MENU" << endl;
cout << "<1> Option A" << endl;
cout << "<2> Option B" << endl;
cout << "<3> Option C" << endl;
cout << "<4> Option D" << endl;
cout << "<5> Option E" << endl;
cout << "\nEnter selection: ";
cin >> selectedOption;
}
while((selectedOption < 1) || (selectedOption > 5));
return selectedOption;
}
-
You can catch anything that's thrown. You can throw an intrinsic type (such as int, bool, char*, whatever) or an object (it's best to derive from the std::exception class for solidarity).
For example:
Code:
try {
throw 5;
throw "Hello";
throw std::logic_error("Arrrrghh");
throw std::runtime_error("Whatsit");
} catch(int i) {
cerr << i << endl;
} catch(const char* str) {
cerr << str << endl;
} catch(std::exception &ex) {
cerr << ex.what() << endl;
}
Comment out the throw statements you don't want.
A quick note - virtual inheritance is taken into account of when passing objects, so you should always pass a reference. In this case, the std::exception will catch both the logic_error and the runtime_error. The what() function is guaranteed in subclasses of exception, and makes a much easier way of telling the user what went wrong.