Multiple Catch Blocks in Function Try Blocks

Can I have multiple catch blocks in a function try block?

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.

Function Try Blocks

Learn about Function Try Blocks, and their importance in managing exceptions in constructors

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Handling Constructor Exceptions
How can I handle exceptions thrown in a constructor?
Return Types in Function Try Blocks
How do I specify a return type for a function that uses a function try block?
Function Try Block vs Regular Try-Catch
When should I use a function try block instead of a regular try-catch block?
Rethrowing Exceptions
What happens if I don't rethrow an exception caught in a function try block?
Catching All Exceptions
How can I catch all exceptions in a function try block?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant