This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, March 17, 2023

Write a program to demonstrate the concept of rethrowing an exception.

 In C++, an exception can be rethrown to be caught by another catch block. This allows for more fine-grained handling of exceptions in a program.

Here is an example program that demonstrates rethrowing an exception:

#include <iostream>
using namespace std;

void divide(int a, int b) {
    try {
        if (b == 0) {
            throw "Division by zero error";
        }
        else {
            cout << "a/b = " << a/b << endl;
        }
    }
    catch (const char* e) {
        cout << "Exception caught in divide(): " << e << endl;
        throw;  // rethrowing the same exception
    }
}

int main() {
    int x = 10, y = 0;
    try {
        divide(x, y);
    }
    catch (const char* e) {
        cout << "Exception caught in main(): " << e << endl;
    }
    return 0;

}

In this program, the divide() function takes two integers as arguments and performs a division operation. If the second argument is 0, it throws a "Division by zero error" exception.

The main() function calls divide() with x=10 and y=0, which should trigger the exception. The catch block in main() catches the exception and prints an error message.

However, before the exception is caught in main(), it is caught in the divide() function's catch block. Instead of handling the exception, the divide() function rethrows the same exception using the throw statement. This allows the exception to be caught by the main() function's catch block.

The output of this program is:

Exception caught in divide(): Division by zero error
Exception caught in main(): Division by zero error

As we can see, the exception is caught first by the divide() function's catch block and then by the main() function's catch block. This demonstrates the concept of rethrowing an exception.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget