Exception handling

My program asks a user for input and I want to throw an out_of_range exception if they give me something not in the expected range. This is what I have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
char letterGrade;
cout << "Enter a letter: " << endl;
cin >> letterGrade;

try{
gpa = gpa(letterGrade);
}
catch(out_of_range oor){
cout << "Invalid input!"  << endl;
}

}


Am I handling the exception correctly? What would be a way to keep asking the user for a letter grade until they enter a correct one?

Thanks
It would be much cleaner if you checked the arguments before handing them to the function. That would also eradicate the need for an exception there. And you might wanna catch the oor by reference - I doubt it matters that much, but you never know.

Other than that, this would probably work I guess. And repeating? Just put the whole thing in a loop and break out of it once you got okay-ish input.
So by "checking before" do you mean wrapping the
cin >> letterGrade

in a try catch?
No, I mean simply checking whether the letterGrade you get is a valid value to pass to gpa. Wrapping it in a try/catch block isn't going to do anything because cin >> letterGrade won't throw unless you specified that it should, and even then it will only throw if the input is not a character (which is, to say the least, rather unlikely).
Topic archived. No new replies allowed.