Sometimes in code I see throwing exceptions where the throw
keyword is used without an expression next to it:
throw;
What does it mean and when should I use it?
Sometimes in code I see throwing exceptions where the throw
keyword is used without an expression next to it:
throw;
What does it mean and when should I use it?
An empty throw
rethrows the exception.
It can appear only in a catch
or in a function called from a catch
.
If an empty throw
is encountered when a handler is not active, terminate
will be called.
It rethrows the exception of the currently active catch
block.
try {
foo();
} catch (...) {
fix_some_local_thing();
throw; // keep searching for an error handler
}
If there is no currently active catch
block, it will call std::terminate
.
It's a rethrow of the current exception.
This doesn't alter the current exception, effectively just resuming the stack-unwinding after doing the actions in your catch{} block.
Quoting the standard: § 15.1 ad 8 [except.throw]
A throw-expression with no operand rethrows the currently handled exception (15.3). The exception is reactivated with the existing temporary; no new temporary exception object is created. The exception is no longer considered to be caught; therefore, the value of
std::uncaught_exception()
will again be true.Example: code that must be executed because of an exception yet cannot completely handle the exception can be written like this:
try { // ... } catch (...) { // catch all exceptions // respond (partially) to exception throw; // pass the exception to some // other handler }
In a function declaration, it means that the function won't throw any exception.
In a catch
block, it re-throws the caught exception, e.g.
try {
throw "exception";
catch ( ... ) {
std::cout << "caught exception";
throw; // Will rethrow the const char* exception
}