In C++, multiple catch blocks are used to handle different types of exceptions that might be thrown in a try block. Each catch block is designed to handle a specific type of exception. You can have multiple catch blocks to catch different exceptions or catch exceptions in different ways.
Syntax:
try {
// Code that may throw exceptions
}
catch (exceptionType1 &e1) {
// Code to handle exceptionType1
}
catch (exceptionType2 &e2) {
// Code to handle exceptionType2
}
catch (...) {
// Code to handle all other exceptions
}
Example:
#include <iostream>
#include <stdexcept> // For std::runtime_error
int main() {
try {
int a=10, b=0;
if (b == 0) {
throw std::runtime_error("Error: Division by zero");
} else if (b < 0) {
throw std::invalid_argument("Error: second value should not be negative.");
}
double result = a/b;
std::cout << "Result: " << result << std::endl;
}
catch (std::runtime_error &e) {
std::cout << "Caught a runtime_error: " << e.what() << std::endl;
}
catch (std::invalid_argument &e) {
std::cout << "Caught an invalid_argument exception: " << e.what() << std::endl;
}
catch (...) {
std::cout << "Caught an unknown exception." << std::endl;
}
return 0;
}
Exceptions:
- If the divisor is zero, it throws a std::runtime_error.
- If values b's value is negative, it throws a std::invalid_argument exception.
- If any other unexpected exception occurs, the catch-all handler catch (…) will catch it.
Output:
Caught a runtime_error: Error: Division by zero
if b value is negative like b=-5 then output
Caught an invalid_argument exception: Error: second value should not be negative.