Here's an example program that uses multiple catch statements to handle different types of exceptions:
#include <string>
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:
Error: Cannot divide by zero!
And another example output where the division is successful:
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