CKTIS / C++
throw — throwing and rethrowing exceptions
The throw keyword throws an exception from an expression or rethrows the currently handled exception. Learn the distinction between throw expression; and throw;, how stack unwinding works, and which situations lead to std::terminate.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
throw expression;
throw;throw expression; creates an exception object and starts transferring control to a matching catch. The throw expression itself has type void; the semicolon ends the statement. An exception need not derive from a library class — the example uses Error.
throw; rethrows the currently handled exception without creating a new object. Without such an exception, it calls std::terminate. Do not casually replace it with throw e;: that form initializes a new object from the expression e and can slice away the derived portion when e refers to a base class.
Handlers are checked in source order; catch (...) matches any exception and must come last. Catching class objects by const reference, as in const Error&, avoids copying the handler parameter. During stack unwinding toward a handler, constructed automatic objects in exited scopes are destroyed in reverse order of completion of their construction.
No matching handler, or propagation out of a noexcept function, leads to std::terminate; do not assume full stack unwinding in those cases. An exception escaping a destructor invoked directly by stack unwinding also leads to std::terminate. A destructor called indirectly as part of cleanup can throw without triggering this rule if the exception is caught before it escapes the directly invoked destructor. This entry targets C++23; the supplied sources are an evolving working draft, not a frozen C++23 publication.
Examples
#include <iostream>
struct Error {
int code;
};
void fail() {
try {
throw Error{7};
} catch (const Error&) {
std::cout << "rethrow\n";
throw;
}
}
int main() {
try {
fail();
} catch (const Error& e) {
std::cout << "caught " << e.code << '\n';
}
}
Result
rethrow caught 7
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.