Can you please Illustrate Rethrowing exceptions?
Submitted by: AdministratorRethrowing 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();
Submitted by: Administrator
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();
Submitted by: Administrator
Read Online C++ Exception Handling Job Interview Questions And Answers
Top C++ Exception Handling Questions
☺ | How to implement exception handling in C++? |
☺ | Explain unexpected() function? |
☺ | Explain terminate() function? |
☺ | Explain benefits of Exception Handling? |
☺ | What is Asynchronous Exceptions? |
Top C Plus Plus Language Categories
☺ | C++ Pointers & Functions Interview Questions. |
☺ | C++ Operator Overloading Interview Questions. |
☺ | C++ Exception Handling Interview Questions. |
☺ | C++ Virtual Functions Interview Questions. |
☺ | C++ Template Interview Questions. |