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 that illustrates the application of multiple catch statements.

 Here's an example program that uses multiple catch statements to handle different types of exceptions:

#include <iostream>
#include <string>
using namespace std;

int main() {
    try {
        int num1, num2, result;

        cout << "Enter two numbers to divide: ";
        cin >> num1 >> num2;

        if (num2 == 0) {
            throw string("Cannot divide by zero!");
        }
        result = num1 / num2;
        cout << "Result: " << result << endl;
    } catch (string errorMessage) {
        cout << "Error: " << errorMessage << endl;
    } catch (...) {
        cout << "Unknown error occurred." << endl;
    }
    return 0;
}

In this program, we ask the user to enter two numbers and attempt to divide them. If the second number is zero, we throw a string exception with an appropriate error message. We then use two catch statements to handle exceptions: the first catches any string exception and prints the error message, while the second catches any other type of exception (or even no exception at all) and prints a generic error message.

Here's an example output of the program:

Enter two numbers to divide: 10 0
Error: Cannot divide by zero!

And another example output where the division is successful:

Enter two numbers to divide: 12 4
Result: 3

As you can see, when an exception is thrown, the program jumps immediately to the catch block that can handle it. If no catch block can handle the exception (such as in the case of an unexpected type of exception), the program will terminate and print an error message.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget