Try-catch block?

I made use of Java try-catch blocks a lot when I programmed in java, and now that I'm working on a c++ program, I want to make use of it as well. How can I use a try-catch block to catch possible input mismatch? This is what I have:

1
2
3
4
5
6
7
8
int main(){
  string entry
  cout << "Enter some numbers: " << endl;
  
  checkForNumerical(string entry); // this function checks to see if the input          
                                   // is numerical, crashes if not.
return 0;
}


The code is a simplified version for the sake of not having to explain my real code.

How can I wrap my checkForNumerical function in a try-catch block to catch the times where the user inputs letters instead of numbers (or user inputs nothing)?
An exception has to be thrown for an exception to be caught. Assuming checkForNumerical() throws and exception (with throw()), detect it with try and handle it with catch.

Does checkForNumerical() actually thrown an exception?

Wazzak
Hmmm thanks. I was under the assumption that when I put something in my try block, it would jump to the catch block if an exception occurred. Where could I find out which exception I need to throw? Is there a way to find out which exception I need to throw (I'm using visual studio 2010)?
hopesfall wrote:
I was under the assumption that when I put something in my try block, it would jump to the catch block if an exception occurred. (sic)

That is what happens. The try block listens out for exceptions. When an exception is thrown, you have to have the correct catch handler for the thrown exception.

hopesfall wrote:
Where could I find out which exception I need to throw? (sic)

There's no specific exception. An exception can be anything from enumerators to a char. You can even make your own exception class.

Wazzak

Topic archived. No new replies allowed.