An exception is a problem that arises during the execution of
a program. A C++ exception is a response to an exceptional circumstance that
arises while a program is running, such as an attempt to divide by zero.
C++ exception handling mechanism provides three keywords.
try
catch
throw
try:
represents a block of code that can throw an exception. It's
followed by one or more catch blocks.
catch:
A program catches an exception with an exception handler at
the place in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.
try
{
statement1;
statement2;
}
catch(argument)
{
statement3;
}
throw:
Used to throw an
exception.
Syntax of
throw statement
throw (excep);
throw excep;
throw; //re-throwing of an exception
Example 1:
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
float d;
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;
try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}
catch(int i)
{
cout<<"Answer is infinite because
a-b is:"<<i;
}
system("PAUSE");
return 0;
}
Catch All
Exception
There is a special catch block called “catch all’ catch(…)
that can be used to catch all types of exceptions.
#include<iostream>
using namespace std;
void test(int x)
{
try
{
if(x==1)
throw
x; //int
else if(x==0)
throw
'x'; //char
else if(x==-1)
throw
1.0; //double
cout<<"End of try block \n";
}
catch(...)
{
cout<<"Caught an
exception\n";
}
}
int main()
{
cout<<"Testing Generic Catch\n";
test(1);
test(0);
test(-1);
return 0;
}

No comments:
Post a Comment