Professional Documents
Culture Documents
throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.
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)
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.
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