1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
Before contrasting the traditional bf(C) way of handling non-local gotos with
exceptions let's introduce the i(syntactic elements) that are involved when
using exceptions.
itemization(
it() Exceptions are generated by a ti(throw) statement. The keyword
tt(throw), followed by an expression of a certain type, throws the expression
value as an exception. In bf(C++) anything having value semantics may be
thrown as an exception: an tt(int), a tt(bool), a tt(string), etc. However,
there also exists a em(standard exception) type (cf. section ref(STDEXC)) that
may be used as em(base class) (cf. chapter ref(INHERITANCE)) when defining new
exception types.
it() Exceptions are generated within a well-defined local environment,
called a tt(try)-block. The run-time support system ensures that all of the
program's code is itself surrounded by a emi(global tt(try) block). Thus, every
exception generated by our code will always reach the boundary of at least one
tt(try)-block. A program terminates when an exception reaches
the boundary of the global tt(try) block, and when this happens destructors of
local and global objects that were alive at the point where the exception was
generated are not called. This is not a desirable situation and therefore all
exceptions should be generated within a tt(try)-block explicitly defined by
the program. Here is an example of a string exception thrown from within a
tt(try)-block:
verb(try
{
// any code can be defined here
if (someConditionIsTrue)
throw "this is the std::string exception"s;
// any code can be defined here
})
iti(catch): Immediately following the tt(try)-block, one or more
tt(catch)-clauses must be defined. A tt(catch)-clause consists of a
catch-header defining the type of the exception it can catch followed by a
compound statement defining what to do with the caught exception:
verb(catch (string const &msg)
{
// statements in which the caught string object are handled
})
Multiple tt(catch) clauses may appear underneath each other, one for each
exception type that has to be caught. In general the tt(catch) clauses may
appear in any order, but there are exceptions requiring a specific order. To
avoid confusion it's best to put a tt(catch) clause for the most general
exception last. At most em(one) exception clause will be activated. bf(C++)
does not support a bf(Java)-style tt(finally)-clause activated after
completing a catch clause.
)
|