C++ catch all exceptions
In some situations, we may not be able to anticipate all types of exceptions and therefore also may not be able to design independent catch handlers to catch them.
In such circumstances, but we can force the catch statement to catch all the
exceptions instead of a certain type alone. This could be achieved by defining the catch statement using ellipses as follows
CATCHING ALL Exceptions
<iostream>
using namespace std;
test( x)
{
{
(x==0) x;
(x==-1) 'x';
(x==1) 1.0;
}
(....)
{
cout << "Caught an exception \n";
}
}
main()
{
cout << "Testing generic catch \n";
test(-1);
test(0);
test(1);
}
|
the output is :
Testing Generic Catch
caught an exception
caught an exception
caught an exception
|
Note: that all the throws were caught by the catch(….) statement
It may be a good idea to use the catch(….) as a default statement along with other catch handlers
so that it can catch all those exceptions which are not handled explicitly.
Note: Remember catch(…) should always be placed last in the list of handlers.
placing it before other catch blocks would prevent those blocks from catching exception