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 main program that calls a deeply nested function containing an exception. Incorporate necessary exception handling mechanism.

 Here's an example program that demonstrates a deeply nested function containing an exception, and incorporates exception handling:

#include <iostream>
using namespace std;

void functionC()
{
    // A divide-by-zero exception will be thrown here
    int x = 10, y = 0, z = x/y;
}

void functionB()
{
    functionC();
}

void functionA()
{
    functionB();
}

int main()
{
    try
    {
        functionA();
    }
    catch(const exception& e)
    {
        cerr << "Exception caught: " << e.what() << '\n';
    }
    return 0;
}

In this program, functionC() performs a divide-by-zero operation, which throws an exception. functionC() is called by functionB(), which is called by functionA(), which is called from main().

The try block in main() calls functionA(), which may throw an exception. If an exception is thrown, it is caught by the catch block, which prints an error message to the console. In this case, the error message will indicate that a divide-by-zero exception was caught.

If we run the program, we will see the following output:

Exception caught: integer division or modulo by zero

This indicates that the exception was caught and handled properly.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget