General topics | ||||||||||||||||
Flow control | ||||||||||||||||
Conditional execution statements | ||||||||||||||||
Iteration statements (loops) | ||||||||||||||||
Jump statements | ||||||||||||||||
Functions | ||||||||||||||||
Function declaration | ||||||||||||||||
Lambda function expression | ||||||||||||||||
inline specifier | ||||||||||||||||
Dynamic exception specifications(until C++17*) | ||||||||||||||||
noexcept specifier(C++11) | ||||||||||||||||
Exceptions | ||||||||||||||||
| ||||||||||||||||
Namespaces | ||||||||||||||||
Types | ||||||||||||||||
Specifiers | ||||||||||||||||
| ||||||||||||||||
Storage duration specifiers | ||||||||||||||||
Initialization | ||||||||||||||||
Expressions | ||||||||||||||||
Alternative representations | ||||||||||||||||
Literals | ||||||||||||||||
Boolean -Integer -Floating-point | ||||||||||||||||
Character -String -nullptr(C++11) | ||||||||||||||||
User-defined(C++11) | ||||||||||||||||
Utilities | ||||||||||||||||
Attributes(C++11) | ||||||||||||||||
Types | ||||||||||||||||
typedef declaration | ||||||||||||||||
Type alias declaration(C++11) | ||||||||||||||||
Casts | ||||||||||||||||
Memory allocation | ||||||||||||||||
Classes | ||||||||||||||||
Class-specific function properties | ||||||||||||||||
| ||||||||||||||||
Special member functions | ||||||||||||||||
Templates | ||||||||||||||||
Miscellaneous | ||||||||||||||||
General | ||||
Literals | ||||
Operators | ||||
Conversions | ||||
try block | ||||
Throwing exceptions | ||||
Handling exceptions | ||||
Exception specification | ||||
noexcept specification(C++11) | ||||
dynamic specification(until C++17*) | ||||
noexcept operator(C++11) |
Throwing anexception transfers control to ahandler.
An exception can be thrown fromthrow expressions, the following contexts may also throw exceptions:
Contents |
Throwing an exception initializes an object with dynamicstorage duration, called theexception object.
If the type of the exception object would be one of the following types, the program is ill-formed:
Given the type of the exception object asT
:
T
fromobj must be well-formed.T
is a class type:T
ispotentially invoked.The memory for the exception object is allocated in an unspecified way. The only guarantee is that the storage will never be allocated by globalallocation functions.
If ahandler exits byrethrowing, control is passed to another handler for the same exception object. The exception object is not destructed in this case.
When the last remaining active handler for the exception exits by any means other than rethrowing, the exception object is destroyed and the implementation may deallocate the memory for the temporary object in an unspecified way. The destruction occurs immediately after the destruction of the object declared in the “parameter list” in the handler. | (until C++11) |
The points of potential destruction for the exception object are:
Among all points of potential destruction for the exception object, there is an unspecified last one where the exception object is destroyed. All other pointshappen before that last one. The implementation may then deallocate the memory for the exception object in an unspecified way. | (since C++11) |
throw expression | (1) | ||||||||
throw | (2) | ||||||||
expression | - | the expression used to construct the exception object |
When a new exception is thrown, its exception object is determined as follows:
If a program attempts to rethrow an exception when no exception is presently being handled,std::terminate will be invoked. Otherwise, the exception is reactivated with the existing exception object (no new exception object is created), and the exception is no longerconsidered to be caught.
try{// throwing a new exception 123throw123;}catch(...)// catch all exceptions{// respond (partially) to exception 123throw;// pass the exception to some other handler}
Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of atry block, at which point the parameters of all associated handlers are compared, in order of appearance, with the type of the exception object to find amatch. If no match is found, the control flow continues to unwind the stack until the nexttry block, and so on. If a match is found, the control flow jumps to the matching handler.
As the control flow moves up the call stack, destructors are invoked for all objects withautomatic storage duration that are constructed, but not yet destroyed, since the correspondingtry block was entered, in reverse order of completion of their constructors. If an exception is thrown from a destructor of a local variable or of a temporary used in areturn statement, the destructor for the object returned from the function is also invoked.
If an exception is thrown from a constructor or (rare) from a destructor of an object (regardless of the object's storage duration), destructors are called for all fully-constructed non-static non-variant members and base classes, in reverse order of completion of their constructors. Variant members ofunion-like classes are only destroyed in the case of unwinding from constructor, and if the active member changed between initialization and destruction, the behavior is undefined.
If a delegating constructor exits with an exception after the non-delegating constructor successfully completed, the destructor for this object is called. | (since C++11) |
If the exception is thrown from a constructor that is invoked by anew-expression, the matchingdeallocation function is called, if available.
This process is calledstack unwinding.
If any function that is called directly by the stack unwinding mechanism, after initialization of the exception object and before the start of the exception handler, exits with an exception,std::terminate is called. Such functions includedestructors of objects with automatic storage duration whose scopes are exited, and the copy constructor of the exception object that is called (if notelided) to initialize catch-by-value arguments.
If an exception is thrown and not caught, including exceptions that escape the initial function ofstd::thread, the main function, and the constructor or destructor of any static or thread-local objects, thenstd::terminate is called. It is implementation-defined whether any stack unwinding takes place for uncaught exceptions.
When rethrowing exceptions, the second form must be used to avoid object slicing in the (typical) case where exception objects use inheritance:
try{std::string("abc").substr(10);// throws std::out_of_range}catch(conststd::exception& e){std::cout<< e.what()<<'\n';// throw e; // copy-initializes a new exception object of type std::exceptionthrow;// rethrows the exception object of type std::out_of_range}
Thethrow-expression is classified asprvalue expression of typevoid. Like any other expression, it may be a sub-expression in another expression, most commonly in theconditional operator:
double f(double d){return d>1e7?throwstd::overflow_error("too big"): d;} int main(){try{std::cout<< f(1e10)<<'\n';}catch(conststd::overflow_error& e){std::cout<< e.what()<<'\n';}}
#include <iostream>#include <stdexcept> struct A{int n; A(int n=0): n(n){std::cout<<"A("<< n<<") constructed successfully\n";} ~A(){std::cout<<"A("<< n<<") destroyed\n";}}; int foo(){throwstd::runtime_error("error");} struct B{ A a1, a2, a3; B()try: a1(1), a2(foo()), a3(3){std::cout<<"B constructed successfully\n";}catch(...){std::cout<<"B::B() exiting with exception\n";} ~B(){std::cout<<"B destroyed\n";}}; struct C: A, B{ C()try{std::cout<<"C::C() completed successfully\n";}catch(...){std::cout<<"C::C() exiting with exception\n";} ~C(){std::cout<<"C destroyed\n";}}; int main()try{// creates the A base subobject// creates the a1 member of B// fails to create the a2 member of B// unwinding destroys the a1 member of B// unwinding destroys the A base subobject C c;}catch(conststd::exception& e){std::cout<<"main() failed to create C with: "<< e.what();}
Output:
A(0) constructed successfullyA(1) constructed successfullyA(1) destroyedB::B() exiting with exceptionA(0) destroyedC::C() exiting with exceptionmain() failed to create C with: error
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
CWG 499 | C++98 | an array with unknown bound could not be thrown because its type is incomplete, but an exception object can be created from the decayed pointer without any problem | apply the type completion requirement to the exception object instead |
CWG 668 | C++98 | std::terminate was not called if an exception is thrown from the destructor of a local non-automatic object | callstd::terminate in this case |
CWG 1863 | C++11 | copy constructor was not required for move-only exception objects when thrown, but copying allowed later | copy constructor required |
CWG 1866 | C++98 | variant members were leaked on stack unwinding from constructor | variant members destroyed |
CWG 2176 | C++98 | throw from a local variable destructor could skip return value destructor | function return value added to unwinding |
CWG 2699 | C++98 | throw"EX" would actually throwchar* rather thanconstchar* | corrected |
CWG 2711 | C++98 | the source of the copy-initialization of the exception object was not specified | copy-initialized fromexpression |
CWG 2775 | C++98 | the exception object copy-initialization requirement was unclear | made clear |
CWG 2854 | C++98 | the storage duration of exception objects was unclear | made clear |
P1825R0 | C++11 | implicit move from parameters was forbidden inthrow | allowed |
(until C++17) |