Using try catch

I am trying to make a try catch where if a user enters a char into an int it catches it and returns an error message. How do I specify catch a char in the catch block?

thanks
You need to set the exception bits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
  {
  cin.exceptions( ios::failbit );

  int n;
  cout << "Enter an integer (but really enter a character): ";
  try
    {
    cin >> n;
    }
  catch (const exception& e)
    {
    cout << "Good job! You entered the wrong thing!\n"
            "The error message I got was: \"" << e.what() << "\"\n";
    return 0;
    }

  cout << "What?! You entered the integer " << n << ".\n";
  return 1;
  }

Hope this helps.

[edit]
After posting this, I remember that you should be aware that this approach has all the same troubles as doing it without the exceptions. Try entering something like "12abc" to see what I mean.

The real solution is something like:
http://www.cplusplus.com/forum/beginner/13044/#msg62827
Last edited on
Topic archived. No new replies allowed.