6.4 KiB
[except.pre]
14 Exception handling [except]
14.1 Preamble [except.pre]
Exception handling provides a way of transferring control and information from a point in the execution of a thread to an exception handler associated with a point previously passed by the execution.
A handler will be invoked only by throwing an exception in code executed in the handler's try block or in functions called from the handler's try block.
try-block:
try compound-statement handler-seq
function-try-block:
try ctor-initializeropt compound-statement handler-seq
handler-seq:
handler handler-seqopt
handler:
catch ( exception-declaration ) compound-statement
exception-declaration:
attribute-specifier-seqopt type-specifier-seq declarator
attribute-specifier-seqopt type-specifier-seq abstract-declaratoropt
...
The optional attribute-specifier-seq in an exception-declaration appertains to the parameter of the catch clause ([except.handle]).
A try-block is a statement ([stmt.pre]).
[Note 1:
Within this Clause âtry blockâ is taken to mean both try-block andfunction-try-block.
â end note]
The compound-statement of a try block or of a handler is a control-flow-limited statement ([stmt.label]).
[Example 1: void f() {goto l1; // errorgoto l2; // errortry {goto l1; // OKgoto l2; // error l1: ; } catch (...) { l2: ; goto l1; // errorgoto l2; // OK}} â end example]
Agoto,break,return, orcontinue statement can be used to transfer control out of a try block or handler.
When this happens, each variable declared in the try block will be destroyed in the context that directly contains its declaration.
[Example 2: lab: try { T1 t1; try { T2 t2; if (condition)goto lab; } catch(...) { /* handler 2 / }} catch(...) { / handler 1 */ }
Here, executinggoto lab; will destroy firstt2, thent1, assuming thecondition does not declare a variable.
Any exception thrown while destroyingt2 will result in executinghandler 2; any exception thrown while destroyingt1 will result in executinghandler 1.
â end example]
Afunction-try-block associates ahandler-seq with thector-initializer, if present, and thecompound-statement.
An exception thrown during the execution of thecompound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class's subobjects, transfers control to a handler in afunction-try-block in the same way as an exception thrown during the execution of atry-block transfers control to other handlers.
[Example 3: int f(int);class C {int i; double d;public: C(int, double);};
C::C(int ii, double id)try : i(f(ii)), d(id) {// constructor statements} catch (...) {// handles exceptions thrown from the ctor-initializer and from the constructor statements} â end example]
In this Clause, âbeforeâ and âafterâ refer to theâsequenced beforeâ relation.