In some situations the program segment has more than one condition to throw an exception.In such case more than one catch blocks can be associated with a try block as shown below
try
{//try block
}
catch(type1 arg)
//catch block1
}
catch(type 2 arg)
{
//catch block 2
}
……………..
…………….
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. After executing the handler, the control goes to the first
statement after the last catch block for that try. When no match is found, the
program is terminated.
If in some case the arguments of several catch
statements match the type of an exception, then the first handler that matches
the exception type is executed.
Catch All Exceptions:-
In some cases when all possible type of exceptions cannot be
anticipated and may not be able to design independent catch handlers to catch
them, in such situations a single catch statement is forced to catch all
exceptions instead of certain type alone. This can be achieved by defining the
catch statement using ellipses as follows
catch(. . .)
{
//statement for processing all exceptions
}
Example:
#include <iostream.h>
void test(int x)
{
try
{
if (x== 0) throw x; //int
if ( x== -1) throw ‘x’; //char
if ( x== 1) throw 1.0; //float
}
catch(. . .) //catch all
{
cout<<”caught an exception \n”;
}
}
int main()
{
cout<<”testing generic catch\n”;
test(-1);
test(0);
test(1);
}
The catch(. . .) can be used as a default statement along
with other catch handlers so that it can catch all those exceptions that are
not handled explicitly.
No comments:
Post a Comment