Exception Handling in C++: Rethrowing Exceptions

After an exception is caught, it can be rethrown to the caller of the function.

C++ allows an exception handler to rethrow the exception if it cannot process it or simply wants to let its caller be notified. The syntax may look like this:

try

{

statements;

}

catch (TheException& ex)

{

perform operations before exits; throw;

}

The statement throw rethrows the exception so that other handlers get a chance to process it. Listing 16.15 gives an example that demonstrates how to rethrow exceptions.

Listing 16.15 RethrowExceptionDemo.cpp

1 #include <iostream>
2
#include <stdexcept>
3
using namespace std;
4

5 int f1()
6 {
7     
try
8     {
9       
throw runtime_error(“Exception in f1”);
10    }
11   
catch (exception& ex)
12    {
13        cout <<
“Exception caught in function f1” << endl;
14        cout << ex.what() << endl;
15       
throw; // Rethrow the exception
16    }
17 }
18
19
int main()
20 {
21   
try
22    {
23       f1();
24    }
25   
catch (exception& ex)
26    {
27       cout <<
“Exception caught in function main” << endl;
28       cout << ex.what() << endl;
29    }
30
31   
return 0;
32 }

The program invokes function f1 in line 23, which throws an exception in line 9. This exception is caught in the catch block in line 11, and it is rethrown to the main function in line 15. The catch block in the main function catches the rethrown exception and processes it in lines 27-28.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *