Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack).
An exception can be thrown by a throw-expression, dynamic_cast, typeid, new-expression, allocation function, and any of the standard library functions that are specified to throw exceptions to signal certain error conditions (e.g. std::vector::at
, std::string::substr
, etc).
In order for an exception to be caught, the throw-expression has to be inside a try-block or inside a function called from a try-block, and there has to be a catch clause that matches the type of the exception object.
When declaring a function, exception specifications and noexcept specifiers may be provided to limit the types of the exceptions a function may throw.
Errors that arise during exception handling are handled by std::terminate
and std::unexpected
(until C++17).
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.
Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following[1][2][3]:
In particular, this implies that the failures of constructors (see also RAII) and most operators should be reported by throwing exceptions.
In addition, so-called wide contract functions use exceptions to indicate unacceptable inputs, for example, std::string::at
has no preconditions, but throws an exception to indicate index out of range.
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[4][5][6], which are strict supersets of each other:
std::vector::push_back
) Generic components may, in addition, offer exception-neutral guarantee: if an exception is thrown from a template parameter (e.g. from the Compare
function object of std::sort
or from the constructor of T
in std::make_shared
), it is propagated, unchanged, to the caller.
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.[7][8][9]
To avoid unnecessary copying of the exception object and object slicing, the best practice for catch clauses is to catch by reference.[10][11][12][13]
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/language/exceptions