Re-throwing Exception and Exception Specifications, Custom| OOP in C++


Re-throwing an exception


In re-throwing exception an exception handler may re-throw the exception caught, to do so, throw keyword is written without any argument, the control comes out from current try/catch block and enters into next try/catch block, listed in the program.
In the following division program, if the value of divisor is zero, re-throwing exception caught, is done in code below.


void divide (double x, double y)
{
cout<<"\n Inside divide function";
try
{
if(y==0.0)
{
throw y;
}
else
{
cout<<"\n Division ="<<x/y;
}}
catch(double )
{
cout<<"\n caught double inside division and rethrowing it";
throw;
}
cout<<"\n End of division";
}
int main()
{
cout<<"\n Inside main()";
try
{
divide(5.0, 2.0);
divide(5.0, 0.0);
}
catch(double)
{
cout<<"\n caught double inside main()";
}
cout<<"\n End of main()";
}
Output:


Specifying Exception


It is possible to allow or restrict certain exception in c++.To do so, a throw list should be included with function definition as
type function(arg-list) throw(type-list)
{
//////
}
If we do not want to throw any exception then make throw list empty as

type function(args-list) throw()
{
//
}
Note:- A function can only be restricted in that type of exceptions which it throws back to the try block that called it. The restriction applies only when throwing an exception out of the function and not within the function.

Custom Search

%d bloggers like this: