Rethrowing exceptions with an example - C++

Illustrate Rethrowing exceptions with an example.

- Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block.
- Consider the following code :
#include <iostream>
using namespace std;
void MyHandler()
{
   try
   {
       throw “hello”;
   }
   catch (const char*)
   {
   cout <<”Caught exception inside MyHandler\n”;
   throw; //rethrow char* out of function
   }
}
int main()
{
   cout<< “Main start”;
   try
   {
       MyHandler();
   }
   catch(const char*)
   {
      cout <<”Caught exception inside Main\n”;
   }
       cout << “Main end”;
       return 0;
}
Output :
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
- Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();
What is a base class?
What is a base class? - Inheritance is one of the important features of OOP which allows us to make hierarchical classifications of classes....
What is private inheritance? - C++
What is private inheritance? - When a class is being derived from another class, we can make use of access specifiers....
What is protected inheritance? - C++
What is protected inheritance? - When a class is being derived from another class, we can make use of access specifiers...
Post your comment