25 Nov 2019

  • November 25, 2019
  • Amitraj
Rethrowing an Exception in C++

-> A handler may decide to rethrow the exception caught without processing it. In such situations, we may simply invoke throw without any arguments as shown below:
      throw;
    
    This  causes the current exception to be thrown to the next enclosing try / catch sequence and is caught by a catch statement listed after that enclosing try block.


// C++ program to rethrow an exception.

#include<iostream>
using namespace std;
void divide(double x,double y)
{
cout<<"Inside function\n";
try
{
if(y==0.0)
throw y;
else
cout<<"Division="<<x/y<<"\n";
}
   catch(double)
   {
       cout<<"Caught double inside function\n";
       throw;
   }
   cout<<"End of function\n";
}

int main()
{
cout<<"Inside main\n";
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{
cout<<"Caught double inside main\n";
}
cout<<"End of main\n";
return 0;

}

OUTPUT:

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


-> When an exception is rethrown, it will not be caught by the same catch statement or any other catch statement in that group. rather, it will be caught by an appropriate catch in the outer try/catch sequence only.



Translate

Popular Posts