Exception handling in C++ is implemented by using try,catch and throw. An example of how these are used is given in the following program :
try { .... } // tries a set of statement to test the presence of an exception
throw(VALUE); // to throw a value in case an exception has occured
catch( ... ) { ... } // to catch the exception and take appropriate steps to handle it. Can have parameters to receive a particular type of value.
#include <iostream>
int main()
{
int x;
std::cout<<" Enter the value of x : ";
std::cin>>x; // prompts the user to enter some value of x
try // try block to test the value of x
{
if ( x > 0 )
throw (0); // throws an integer
else
throw ('a'); // throws a character
}
catch(int n)
{
std::cout<<" \n Caught Integer !!! ";
}
catch(char ch)
{
std::cout<<"\n Caught Character !!!";
}
std::cin.get();
return 0;
} // end of main
Exception handled when x < 0 |
Exception handled when x > 0 |
0 comments:
Post a Comment
Comment Here....