try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws but doesn’t handle itself.
#include <iostream>
using namespace std;
int main()
{
int x = 2;
// Some code
cout << "Before try \n";
try
{
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x )
{
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
#include <iostream>
using namespace std;
float hmean(const float a, const float b);
int main()
{
char choice='y' ;
double x,y,z ;
while(choice=='y')
{
cout<<"Enter a number: " ;
cin>>x;
cout<<"Enter another number: " ;
cin >>y ;
try
{
z=hmean(x,y);
}
catch(char const *s)
{
cout<<s<<endl ;
cout<<"Enter a new pair of numbers\n";
continue;
}
cout<<"Harmonic mean of "<<x<< " and "<<y<< " is "<<z<<endl;
cout<<"continue ? (y/n) ";
cin>>choice;
}
cout<<"Bye\n";
return 0;
}
float hmean(const float a, const float b)
{
if(a==-b)
{
throw "bad arguments to hmean()" ;
}
return 2.0*a*b /(a+b) ;
}