Rethrow An Exception | Exception Handling | C++ Tutorials

12 May 20120 comments

It is possible that a single catch block may not handle an exception completely. In such a situation, the catch block on receiving an exception must pass it to another catch block by rethrowing an exception. The rethrowing expression takes the following from,
                                                    throw ;
The rethrow expression can only appear in the catch block from where it is implicitly propagated to outer try/catch sequence and is caught by that catch block which has the same type parameter. The following program illustrate how an exception is rethrown and caught.

  1. #include<iostream.h>
  2. #include<conio.h>
  3. void funchandler()
  4. {
  5.    try
  6.    {  throw 10; }
  7.    catch(int i)
  8.    {
  9.       cout<<"caught exception  inside function";
  10.       throw;
  11.    }
  12. }
  13. int main()
  14. {
  15.    cout<<"start of mail()\n";
  16.    try
  17.    {
  18.       funchandler();
  19.    }
  20.    catch(int i)
  21.    {
  22.       cout<<"Rethrown exception caught is main()\n";
  23.    }
  24.    cout<<"End of main()";
  25.    return 0;
  26. }
Output
Start of main()
caught exception inside function
Rethrown exception caught in main()
End of main()
Tags : Exception handling in C++, C++ tutorials, Exception handling Tutorials
Share this article :

Post a Comment

 
Copyright © 2011. All Compiler - All Rights Reserved