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.


Related Posts:

  • C++ Stream classes Structure C++ Stream classes Structure -> The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with both the console and disk files, These classes are called Stream classes. -> Str… Read More
  • Containers and Applications of Container Classes in STL Containers:- Containers are objects that hold data. The STL defines Ten containers which are grouped into three categories. 1. Sequence Containers     Sequence containers store elements in a linear sequ… Read More
  • C++ File I/O Operations on Characters C++ File I/O Operations on Characters #include<iostream> using namespace std; #include<fstream> #include<cstring> int main() { char string[80]; cout<<"Enter a string:"; cin>>string; int len… Read More
  • C++ Standered Template Library (STL) C++ Standered Template Library (STL) Template can be used to create generic classes and functions that could extend supports for Generic programming.     -> In order to help the C++ users in generic programming… Read More
  • Components of Standered Template Library (STL) Components of Standered Template Library (STL) The STL contains several components but at its core are 3 key components:-     They are- 1. Container 2. Algorithm 3. Iterators -> The Relatonship between The 3… Read More

Translate

Popular Posts