Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to rethrow an Exception

C++ Code Example — Exception Handling

ADVERTISEMENT

WAP to rethrow an Exception

Objective

Write a C++ program to rethrow an Exception.

Algorithm / Approach

  1. In a function, write a try-catch block.
  2. Inside the inner try, throw a string exception.
  3. Inside the inner catch, print a message, and then use the isolated keyword throw;.
  4. In main(), wrap the function call in an outer try-catch block 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 a catch block 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)
ADVERTISEMENT