Function try blocks and regular try-catch blocks serve different purposes and are used in different scenarios. Here are some guidelines on when to use each:
Use a function try block when:
Use a regular try-catch block when:
Here's an example that illustrates the difference:
#include <iostream>
#include <stdexcept>
class MyClass {
public:
MyClass(int value) try : mValue{value} {
// Constructor body
throw std::exception{"Constructor error"};
} catch (...) {
std::cout << "Exception caught in "
"constructor\n";
throw;
}
void doSomething() {
try {
if (mValue < 0) {
throw std::invalid_argument{
"Negative value"};
}
// Regular function code
} catch (const std::exception& e) {
std::cout << "Exception caught in "
"doSomething(): " << e.what() << "\n";
}
}
private:
int mValue;
};
int main() {
try {
MyClass obj{-5};
obj.doSomething();
} catch (const std::exception& e) {
std::cout << "Exception caught in main(): "
<< e.what() << "\n";
}
}
Exception caught in constructor
Exception caught in doSomething(): Negative value
In this example:
MyClass
 uses a function try block to catch any exceptions thrown during the initialization of mValue
. This is necessary because the member initializer list is outside the constructor body.doSomething()
 function uses a regular try-catch block to catch exceptions within a specific part of the function. This allows for localized exception handling.In the main()
function, a MyClass
object is created with a negative value, which throws an exception in the constructor. The exception is caught and handled in the function try block of the constructor.
Then, when doSomething()
is called, it throws an exception due to the negative value, which is caught and handled within the regular try-catch block inside the function.
So, use function try blocks when you need to catch exceptions in the entire function body or in the member initializer list of a constructor, and use regular try-catch blocks for localized exception handling within a function.
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