Answers

Question and Answer:

  Home  C++ Exception Handling

⟩ Can you please Illustrate Rethrowing exceptions?

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 following code:

#include <iostream>

using namespace std;

void MyHandler()

{

try

{

throw “hello”;

}

catch (const char*)

{

cout <<”Caught exception inside MyHandlern”;

throw; //rethrow char* out of function

}

}

int main()

{

cout<< “Main start”;

try

{

MyHandler();

}

catch(const char*)

{

cout <<”Caught exception inside Mainn”;

}

cout << “Main end”;

return 0;

}

O/p:

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();

 190 views

More Questions for you: