WAP to rethrow an Exception
Objective
Write a C++ program to rethrow an Exception.
Algorithm / Approach
- In a function, write a
try-catchblock. - Inside the inner
try, throw a string exception. - Inside the inner
catch, print a message, and then use the isolated keywordthrow;. - In
main(), wrap the function call in an outertry-catchblock to catch the rethrown exception.
main.cpp
#include<iostream>
using namespace std;
class Test {
public:
void show() {
try {
throw "hello";
}
catch (const char*){
cout <<"Caught IN Function\n";
throw;
}
}
};
int main(){
Test t;
try{
t.show();
}
catch(const char*) {
cout <<"Caught IN Main\n";
}
return 0;
}
Expected Output
Caught IN Function Caught IN Main
Explanation of the Program
- Sometimes, a function can catch an exception, perform some partial cleanup, but still need to pass the error further up the chain to
main()to finish handling it. - Using the
throw;keyword by itself inside acatchblock takes the exact exception that was just caught and instantly re-throws it to the next outer level.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)