Function Try Blocks

Return Types in Function Try Blocks

How do I specify a return type for a function that uses a function try block?

Abstract art representing computer programming

When using a function try block, you specify the return type of the function before the try keyword, just like in a regular function. Here's an example:

#include <stdexcept>

int divideNumbers(int a, int b) try {
  if (b == 0) {
    throw std::invalid_argument{
      "Division by zero"};
  }
  return a / b;
} catch (const std::exception& e) {
  // Handle the exception
  return -1;
}

In this example, the divideNumbers function has a return type of int. The return type is specified before the try keyword.

Inside the function try block, if a division by zero is attempted, an exception is thrown. The catch block catches the exception and returns a value of -1 to indicate an error.

It's important to note that all the catch blocks in a function try block must return a value that is compatible with the function's return type. In this case, both the normal return statement (return a / b;) and the return statement in the catch block (return -1;) return an int value.

If the function has a void return type, then the catch blocks should not return any value.

#include <iostream>
#include <stdexcept>

void printValue(int value) try {
  if (value < 0) {
    throw std::invalid_argument{"Negative value"};
  }
  std::cout << "Value: " << value << "\n";
} catch (const std::exception& e) {
  std::cout << "Exception: " << e.what() << "\n";
  // No return statement needed for void functions
}

In this example, the printValue function has a void return type, so the catch block does not return any value.

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