You are on page 1of 7

Exception Handling

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.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.

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: A try block identifies a block of code for which particular exceptions will be
activated. It's fo/.llowed by one or more catch blocks.

BASICS OF EXCEPTION
The purpose of the exception handling mechanism is to provide means to
detect and report an exception circumstances so that appropriate action can
be taken. The following steps are done
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throw the Exception)
3. Receive an error information(Catch the Exception)
4. Take Corrective Actions(Handle the Exception)

// WAP to show how exceptions are caught


Void main()
{
int a,b;
cin>>a>>b;
int x=a-b;
try
{
if(x!=0)
{
cout<<Result is <<a/x;
}
else
{
throw(x);
// throws in object
}
catch(int i)
{
cout<<Exception is cvaught<<x;
}
getch();
}

Output:
10
10
Exception Caught=0
When the try block throws an exception the program control leaves the try block and enters the
statement of the catch block. Note that exceptions that are being thrown are objects used to
transmit information about a problem. If the type of object thrown matches the arg type in the
catch statement then that block is executed. When no exception is detected and thrown the
control goes to the statement immediately after the catch block.

Multiple Catch Statements

It is possible that a program has more than on condition to throw an exception. In Such cases we
can associate more than one catch statement with a try as shown below:
try
{
//try block
}
catch(type1 arg)
{
catch block1
}
catch(type2 arg)
{
catch block2
}


..
catch(type n arg)
{
catch block n
}

When an exception is thrown the exception handlers are searched in order for an appropriate
match. The first handler that yields a match is executed.

#include <iostream.h>
#include<conio.h>
void main()
{
int x;
cin>>x;
try
{
if(x==1)throw x;
else
if(x==0)throw(x);
else
if(x==-1)throw 1.0;
cout<<"End of try-block \n";
}
catch(char c)
{
cout<<"Caught a character \n";
}
catch(int m)
{
cout<<"Caught an integer \n";
}
catch(double d)
{
cout<<"Caught a double \n";
}
cout<<"End of try-catch system \n\n";
getch();
}

Rethrowing an Exception

Output
Inside main
Inside function
Division=5.25
End of function
Inside function
Caught double inside function
Caught double inside main
End of main

You might also like