Nov 17, 2010 at 3:35pm UTC
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.
Nov 17, 2010 at 5:59pm UTC
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 Nov 17, 2010 at 6:00pm UTC
Nov 18, 2010 at 2:44pm UTC
thx bro.
ur post is really helpful
;)