Yes, you can have multiple catch blocks in a function try block, just like in a regular try-catch block. This allows you to handle different types of exceptions differently. Here's an example:
#include <iostream>
#include <stdexcept>
void processValue(int value) try {
if (value < 0) {
throw std::invalid_argument{"Negative value"};
}
if (value == 0) {
throw std::runtime_error{"Zero value"};
}
std::cout << "Value: " << value << "\n";
} catch (const std::invalid_argument& e) {
std::cout << "Invalid argument: "
<< e.what() << "\n";
} catch (const std::runtime_error& e) {
std::cout << "Runtime error: "
<< e.what() << "\n";
}
int main() {
processValue(42);
processValue(-5);
processValue(0);
}
Value: 42
Invalid argument: Negative value
Runtime error: Zero value
In this example, the processValue
function uses a function try block to catch exceptions. It has two catch blocks: one for std::invalid_argument
exceptions and another for std::runtime_error
 exceptions.
Depending on the value passed to the function, different exceptions are thrown and caught by the corresponding catch block. The appropriate error message is then printed.
This demonstrates how you can use multiple catch blocks in a function try block to handle different types of exceptions separately.
Answers to questions are automatically generated and may not have been reviewed.
Learn about Function Try Blocks, and their importance in managing exceptions in constructors