Function Try Block vs Regular Try-Catch
When should I use a function try block instead of a regular try-catch block?
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:
- You want to catch exceptions that are thrown from the member initializer list of a constructor.
- You want to apply exception handling to the entire function body without explicitly wrapping it in a try block.
Use a regular try-catch block when:
- You want to catch exceptions within a specific block of code inside a function.
- You want to have different exception handling for different parts of the function.
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:
- The constructor of
MyClass
uses a function try block to catch any exceptions thrown during the initialization ofmValue
. This is necessary because the member initializer list is outside the constructor body. - The
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.
Function Try Blocks
Learn about Function Try Blocks, and their importance in managing exceptions in constructors