throw expression

< cpp‎ | language
Revision as of 08:12, 3 January 2014 by Cubbi (Talk | contribs)

Signals an erroneous condition and executes an error handler.



throw expression (1)
throw (2)


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

1) The throw expression constructs a temporary object in unspecified storage, with the same type as expression (with cv-qualifiers removed and the type converted from array of T to pointer to T and from function returning T to pointer to function returning T, as necessary), and initializes it from expression in the same manner as function arguments or return values are initialized from the function parameters or the argument of a return expression (i.e. copy elision and move construction take place if possible). The exception object persists until the last catch clause completes or until the last std::exception_ptr that references this object is destroyed.

Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of the associated catch blocks are compared with the thrown expression to find a match. If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block (the exception handler), which executes normally.

As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration constructed since the corresponding try-block was entered, in reverse order of construction. If an exception is thrown from a constructor, destructors are called for all fully-constructed non-static non-variant members and base classes. This process is called stack unwinding.

2) The throw-expression without an operand may only be used inside a catch block (it calls std::terminate if used otherwise). It abandons the execution of the catch block and passes control to the next matching catch clause up the call stack (but not to another catch clause after the same try block), reusing the existing exception object: no new objects are made.

See std::terminate and std::unexpected for the handling of errors that arise during exception handling.




See also