Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 749

20


creation and removal of resources that might be required to properly handle the
exceptional condition.
Q Why not use exceptions for nonerror conditions? Isn’t it convenient to be able
to express-train back to previous areas of the code, even when nonexceptional
conditions exist?
A Yes, some C++ programmers use exceptions for just that purpose. The danger is
that exceptions might create memory leaks as the stack is unwound and some
objects are inadvertently left in the free store. With careful programming tech-
niques and a good compiler, this can usually be avoided. Otherwise, it is a matter
of personal aesthetic; some programmers feel that, by their nature, exceptions
should not be used for routine conditions.
Q Does an exception have to be caught in the same place where the tryblock
created the exception?
A No, it is possible to catch an exception anywhere in the call stack. As the stack is
unwound, the exception is passed up the stack until it is handled.
Q Why use a debugger when I can use coutand other such statements?
A The debugger provides a much more powerful mechanism for stepping through
your code and watching values change without having to clutter your code with
thousands of debugging statements. In addition, there is a significant risk each time
you add or remove lines from your code. If you have just removed problems by
debugging, and you accidentally delete a real code line when deleting your use of
cout, you haven’t helped the situation.

Workshop ............................................................................................................


The Workshop contains quiz questions to help solidify your understanding of the mater-
ial covered and exercises to provide you with experience in using what you’ve learned.
Try to answer the quiz and exercise questions before checking the answers in Appendix
D, and be certain you understand the answers before going to tomorrow’s lesson.

Quiz ................................................................................................................



  1. What is an exception?

  2. What is a tryblock?

  3. What is a catchstatement?

  4. What information can an exception contain?

  5. When are exception objects created?

Free download pdf