Namespaces
Variants
Views
Actions

throw expression

From cppreference.com
< cpp‎ | language
Revision as of 21:17, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
throw expression
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Signals an erroneous condition and executes an error handler.

Contents

Syntax

throw Template:sparam (1)
throw (2)

Explanation

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 Template:sparam in the same manner a 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 Template:sparam 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.

Usage

While throw-expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to std::longjmp), its intended usage is error handling.

Error handling

Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following[1][2]:

  1. Failures to establish invariants
  2. Failures to meet the postconditions
  3. Failures to meet the preconditions of the caller

In particular, this implies that the failures of constructors and most operators should be reported by throwing exceptions.

Exception safety

After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized[3][4][5], which are strict supersets of each other:

  1. Nothrow (or nofail) exception guarantee -- the function never throws exceptions.
  2. Strong exception guarantee -- If the function throws an exception, the state of the program is rolled back to the state just before the function call.
  3. Basic exception guarantee -- If the function throws an exception, the program is in a valid state. It may require cleanup, but all invariants are intact.
  4. No exception guarantee -- If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.

Exception objects

While objects of any complete type and cv pointers to void may be thrown as exception objects, all standard library functions throw anonymous temporary objects by value, and the types of those objects are derived (directly or indirectly) from std::exception. User-defined exceptions usually follow this pattern.[6][7]

To avoid unnecessary copying of the exception object and object slicing, the best practice for catch clauses is to catch by reference.[8][9][10]

Keywords

throw

Example

References

  1. H. Sutter (2004) "When and How to Use Exceptions" in Dr. Dobb's
  2. H.Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70
  3. B. Stroustrup (2000), "The C++ Programming Language"Appendix E"
  4. H. Sutter (2000) "Exceptional C++"
  5. D. Abrahams (2001) "Exception Safety in Generic Components"
  6. D. Abrahams (2001) "Error and Exception Handling"
  7. M. Cline, C++FAQ Lite 17.11
  8. S. Meyers (1996) "More Effective C++" Item 13
  9. M. Cline, C++FAQ Lite 17.12
  10. H.Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73

See also