CKTIS / C++
try — exception-handling block
The try keyword introduces a block associated with one or more catch handlers. An exception thrown in that block or in a function it calls can transfer control to a matching handler. The function-try-block form also provides handlers for a function body.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
try { /* statements */ }
catch (const Error& e) { /* handle Error */ }
catch (...) { /* handle any other exception */ }
// Function-try-block (constructor form):
// Type::Type() try : member(initializer) { /* body */ }
// catch (...) { /* handle initialization or body failure */ }try introduces a block that must be followed by at least one catch handler. Without an exception, the handlers are skipped. If the block or a function it calls throws, subsequent statements on the interrupted path are not executed. When a matching handler of an ordinary try block finishes normally, execution continues after the whole block; it does not resume at the throw site.
Handlers are tested in source order. Put handlers for derived classes before handlers for their base classes. catch (...) matches any exception and must be the last handler. If none matches, the search continues in a dynamically surrounding try block in the same thread. An exception thrown inside a handler is not handled by sibling handlers of that same block.
During stack unwinding, constructed automatic objects in exited scopes are destroyed in reverse order of construction completion. Use RAII to release resources. try is not a general safeguard against undefined behavior.
A function-try-block replaces an ordinary function body. For a constructor, it also covers base and member initialization, unlike a try placed inside the body. In such a constructor or destructor handler, referring to that object's non-static members or bases has undefined behavior; reaching the end of the handler rethrows the current exception. For a constructor, this does not recover a successfully constructed object.
This description covers syntax available in C++23. The supplied site publishes an evolving working draft, not a frozen C++23 publication. A compiler flag does not attest the production runtime.
Examples
#include <iostream>
struct Error {};
void work() {
throw Error{};
}
int main() {
try {
work();
std::cout << "unreachable\n";
} catch (const Error&) {
std::cout << "caught\n";
}
std::cout << "after\n";
}
Result
caught after
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.