Here's an example program that demonstrates a deeply nested function containing an exception, and incorporates exception handling:
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