Rethrowing an Exception

Rethrowing an exception in C++ involves catching an exception within a try block and instead of dealing with it locally throwing it again to be caught by an outer catch block. By doing this. we preserve the type and details of the exception ensuring that it can be handled at the appropriate level within our program.

This approach becomes particularly valuable when managing exceptions at multiple levels or when additional actions need to be performed before resolving the exception.

To better understand how this works let’s explore an example involving three functions:

Example

C++




#include <iostream>
#include <stdexcept>
using namespace std;
  
// Function to perform division
int divide(int numerator, int denominator)
{
    try {
        if (denominator == 0) {
            // Throw a runtime_error if attempting to divide
            // by zero
            throw runtime_error("Division by zero!");
        }
        // Perform the division and return the result
        return numerator / denominator;
    }
    catch (const exception& e) {
        cout << "Caught exception in divide(): " << e.what()
             << endl;
        // Rethrow the caught exception to handle it at a
        // higher level
        throw;
    }
}
  
// Function to calculate the sum of two numbers
int calculateSum(int a, int b)
{
    try {
        if (a < 0 || b < 0) {
            // Throw an invalid_argument exception for
            // negative numbers
            throw invalid_argument(
                "Negative numbers not allowed!");
        }
        // Calculate and return the sum
        return a + b;
    }
    catch (const exception& e) {
        cout << "Caught exception in calculateSum(): "
             << e.what() << endl;
        // Rethrow the caught exception to handle it at a
        // higher level
        throw;
    }
}
  
int main()
{
    try {
        // Calculate the sum of 10 and the result of
        // dividing 20 by 2
        int result = calculateSum(10, divide(20, 2));
        cout << "Result: " << result << endl;
  
        // Attempt to divide by zero, triggering an
        // exception
        int invalidResult = calculateSum(5, divide(10, 0));
        cout << "Invalid Result: " << invalidResult << endl;
    }
    catch (const exception& e) {
        cout << "Caught exception in main: " << e.what()
             << endl;
        // Handle the exception at the highest level
    }
  
    return 0;
}


Output

Result: 20
Caught exception in divide(): Division by zero!
Caught exception in main: Division by zero!

Explanation:

  • The program first calculates the sum of 10 and the result of dividing 20 by 2, which is 20. This result is printed and there are no exceptions raised in this part.
  • Next, the program attempts to divide by zero when calculating the sum of 5 and the result of dividing 10 by 0. This triggers a “Division by zero!” exception which is caught within the divide() function and rethrown. The rethrown exception is then caught in the main() function and is printed as “Division by zero!” along with the appropriate exception handling messages.

Rethrowing an Exception in C++

Exception handling plays a role in developing robust software in C++. It offers a way to handle errors and unexpected situations. One interesting aspect of exception handling in C++ is the ability to rethrow an exception allowing it to pass up the call stack.

Similar Reads

Rethrowing an Exception

Rethrowing an exception in C++ involves catching an exception within a try block and instead of dealing with it locally throwing it again to be caught by an outer catch block. By doing this. we preserve the type and details of the exception ensuring that it can be handled at the appropriate level within our program....

The Power of Rethrowing Exceptions

...

Contact Us