Function Try Blocks

Multiple Catch Blocks in Function Try Blocks

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Function Try Blocks

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Function Try Blocks

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved