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.
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