In C++, what can a function-try-block on a constructor catch, and why can its handler not stop the exception?
answer
- try before the initializer list
- member and base constructors
- object never finished construction
- end of handler rethrows
basics
~20 sA constructor's function-try-block also covers the member initializer list, so it catches exceptions from base and member constructors. Because the object was never constructed, reaching the end of the handler rethrows the exception, and a return there is ill-formed.
solid answer
~40 sWriting `Importer(const std::string& p) try : schema(p) { ... } catch (...) { ... }` puts the base and member initializers inside the `try`. A plain `try` inside the body cannot do that, because the initializers run before the body starts. When an initializer throws, the already-constructed members and bases are destroyed *before* the handler is entered, so referring to any non-static member or base in the handler is undefined behaviour. The handler cannot produce an object: if control reaches its end the exception is rethrown, and a `return` in it makes the program ill-formed. Its useful jobs are logging, translating the error by throwing a different exception, and freeing resources that were not owned by members, such as a raw pointer argument the constructor took over.
code
cpp · 28 lines#include <iostream>
#include <stdexcept>
#include <string>
struct Schema {
explicit Schema(const std::string& path) {
if (path.empty()) throw std::invalid_argument("empty schema path");
}
};
struct Importer {
Schema schema;
explicit Importer(const std::string& path)
try : schema(path) {
std::cout << "importer ready\n";
} catch (const std::exception& e) {
std::cout << "Importer ctor saw: " << e.what() << '\n';
// falling off the end rethrows the same exception
}
};
int main() {
try {
Importer imp("");
} catch (const std::invalid_argument& e) {
std::cout << "caller caught: " << e.what() << '\n';
}
}go deeper
Recognize the syntax with try before the colon, and know it exists because a try in the body starts too late to see member initializers.
Explain that the handler of a constructor's function-try-block always ends by rethrowing or throwing something else, and that return is ill-formed there.
Use it for logging and translation only, never read members in the handler, and prefer owning parameter types so there is nothing to clean up by hand.
Prefer factory functions or two-phase validation at a boundary when construction failure must be recoverable, and keep constructor function-try-blocks rare and reviewed.
## The syntax and what it covers A **function-try-block** replaces a function body with `try` followed by the body and its handlers. For a constructor the `try` comes *before* the colon of the member initializer list: ```cpp struct Importer { Schema schema; explicit Importer(const std::string& path) try : schema(path) { // constructor body } catch (const std::exception& e) { // handles exceptions from schema(path) and from the body } }; ``` The member initializers and base-class constructors run before the constructor body. A `try` block written *inside* the body therefore cannot catch an exception thrown while initializing `schema`. The function-try-block is the only construct that can. ## What has happened by the time the handler runs If a member or base constructor throws, the language destroys the subobjects that were already fully constructed, in reverse order of construction, and the standard says this destruction is **sequenced before entering the handler** of the function-try-block. So when the handler runs: - every member and base that had been built is already destroyed; - the object itself never began its lifetime as a complete object; - referring to any non-static member or base class of the object in the handler is **undefined behaviour**. ## Why the handler cannot swallow the exception A constructor's job is to produce a valid object, and the handler has nothing valid to produce. The standard therefore says: 1. The currently handled exception **is rethrown if control reaches the end of a handler** of a constructor's or destructor's function-try-block. 2. A `return` statement in a handler of a constructor's function-try-block makes the program **ill-formed**. Clang 21 reports: `error: return in the catch of a function try block of a constructor is illegal`. The handler may still leave by throwing a *different* exception, which is the point of using it for translation. | Function kind | Flowing off the end of the handler | |---|---| | constructor | rethrows the current exception | | destructor | rethrows the current exception | | `main` and other functions | same as flowing off the end of the function body (for `main`, returning 0) | ## What the handler is actually good for - **Logging with context**: recording which configuration path failed before the exception continues. - **Translation**: `throw ImporterError("schema " + path);` or `std::throw_with_nested(...)` to turn a low-level error into one the caller understands. - **Cleaning up what members did not own**: for example a raw pointer parameter whose ownership the constructor was about to take. A better design is to make that a `std::unique_ptr` parameter so nothing needs cleaning. What it is *not* good for is recovering: retry or fall back belongs in the code that creates the object, or in a factory function that returns an empty result on failure. ## Destructors and function-try-blocks A destructor can also have a function-try-block, and the same rule applies: reaching the end of its handler rethrows. Because destructors are implicitly `noexcept` unless a member or base says otherwise, that rethrow normally ends in `std::terminate`, so a destructor function-try-block is almost always a mistake. Handling failure in a destructor belongs to the material on exception-safety guarantees and noexcept. ## Two edge cases - On `main`, a function-try-block does not catch exceptions thrown by destructors of static objects or by constructors of namespace-scope static objects. The same holds for a thread's initial function and the matching thread-storage objects. - Function-try-blocks on ordinary functions are legal but rarely useful; a `try` inside the body does the same job and reads more naturally. The handler can see the function's parameters, and for a non-`void` function other than `main`, flowing off the end of its handler without returning a value is undefined behaviour, exactly like flowing off the end of the body. ## Checklist - Reach for a constructor function-try-block when a member's or base's construction can throw and you need to log or translate. - Never touch members in the handler. - Do not expect the object to exist afterwards; the caller always sees an exception.
- Why is reading a data member inside a constructor's function-try-block handler undefined behaviour?The fully constructed members and bases are destroyed before the handler is entered, and the members that never finished construction never started their lifetime. The standard states that referring to any non-static member or base class of the object in that handler results in undefined behaviour. Anything the handler needs, such as a file path, must come from the constructor's parameters.
- Does a delegating constructor change what the handler sees?Yes. Once the target constructor finishes, the object is complete. If the delegating constructor's body then throws, the object's destructor runs, and that destruction is sequenced before entering the delegating constructor's function-try-block handler. The handler still cannot return normally; the exception is rethrown at the end of the handler.
- A try block inside the constructor body catches exceptions from the member initializer list.
- The handler can return normally and leave a partially built object.
- Members are still alive inside the handler, so they can be logged.
- A function-try-block on main catches exceptions from static objects' constructors.