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
|
Exceptions are bf(C++)'s answer to the problems caused by tt(setjmp) and
tt(longjmp). Here is an example using exceptions. The program is once again
derived from the basic program of section ref(BASICEXCEPTION):
verbinclude(-a examples/exception.cc)
tt(Inner::fun) now throws an tt(int) exception where a tt(longjmp) was
previously used. Since tt(in.fun) is called by tt(out.fun), the exception is
generated within the tt(try) block surrounding the tt(out.fun) call. As an
tt(int) value was thrown this value reappears in the tt(catch) clause beyond
the tt(try) block.
Now tt(Inner::fun) terminates by throwing an exception instead of calling
tt(longjmp). The exception is caught in tt(main), and the program
terminates. Now we see that tt(inner)'s destructor is properly called. It is
interesting to note that tt(Inner::fun)'s execution really terminates at the
tt(throw) statement: The tt(cout) statement, placed just beyond the tt(throw)
statement, isn't executed.
What did this example teach us?
itemization(
it() Exceptions provide a means to break a function's (and program's)
normal flow without having to use a cascade of tt(return)-statements, and
without the need to terminate the program using blunt tools like the function
ti(exit).
it() Exceptions do not disrupt the proper activation of destructors. Since
tt(setjmp) and tt(longjmp) em(do) distrupt the proper activation of
destructors their use is strongly deprecated in bf(C++).
)
|