throw expression

From Cppreference

Jump to: navigation, search

Signals an erroneous condition and executes an error handler.

Contents

[edit] Syntax

throw expression (1)
throw (2)

[edit] Explanation

See try-catch block for more information about try and catch (exception handler) blocks

Executing a throw expression stops the normal flow of the program. The control is transferred to appropriate exception handler (catch block). There is one parameter passed to the exception handler. The first version of the throw expression passes the value of the expression as the parameter. The type of the expression must not be void. The second version passes the value of currently handled exception (thus the second version is allowed only in exception handlers).

The exception handler that the control is passed to is the first catch block in the call stack, accepting the type of expression as its argument. All objects with automatic storage duration, that get out of scope because of control transfer to the exception handler, are destructed. This action is called stack unwinding.

Several erroneous situations can arise during handling of an exception:

  • If no appropriate exception handler is found (no exception handlers in the call stack accept the parameter passed to the throw expression), std::terminate() is called.
  • If during stack unwinding any of the destructors exit via an exception (second exception is thrown when the handling of current exception is unfinished), std::terminate() is called.

[edit] Keywords

throw

[edit] Example

[edit] See also

try-catch block, noexcept specifier, exception specifications