Exception Handling

Hi guys, i am using the exception handling use to catch the errors.
But the program doesn't work as i wish.
I was trying to make a validation, when user try to input string for integer variable, the exception handling can catch it.
Example:
int a;
try
{
cout<<"1"<<endl;
cin>>a;
cout<<a;
system("pause");
}
catch(exception ex)
{
cout<<"Error in configuration. Please contact system support\n Error message:ex"<<endl;
system("pause");
}


Thanks for reading my post.
You didn't throw an exception, see the tutorial http://www.cplusplus.com/doc/tutorial/exceptions/

Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
int a;
try
  {
    cout<<"1"<<endl;
    if( (cin>>a)==false) // cin returns 0 when fails
        throw("Cin failed"); // throw the exception
    cout<<a;
    system("pause");
  }
catch(const char *errmsg) // catch the exception
  {
    cout<<"Error in configuration. Please contact system support\n Error message: "<<errmsg<<endl;
    system("pause");
  }

}


You can derive your own exception class from std::exception
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
class my_exception: public std::exception
{
public:

 string error;
 my_exception(string error)
  {
    this->error=error;
  }
 virtual const char* what() const throw()
  {
   return error.c_str();
  }
  ~my_exception() throw() {};

};



int main()
{
int a;
try
  {
    cout<<"1"<<endl;
    if( (cin>>a)==false)
        throw(my_exception("error message"));
    cout<<a;
    system("pause");
  }
catch(exception &ex) // note that you are catching std::exception instead of my_exception
  {
    cout<<"Error in configuration. Please contact system support\nError message: "<<ex.what()<<endl;
    system("pause");
  }

}



Last edited on
thx bro.
ur post is really helpful
;)
Topic archived. No new replies allowed.