16. Exception Handling

Objectives

In this chapter you'll learn:

  • What exceptions are and when to use them.

  • To use try, catch and throw to detect, handle and indicate exceptions, respectively.

  • To process uncaught and unexpected exceptions.

  • To declare new exception classes.

  • How stack unwinding enables exceptions not caught in one scope to be caught in another scope.

  • To handle new failures.

  • To use auto_ptr to prevent memory leaks.

  • To understand the standard exception hierarchy.

It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something.

Franklin Delano Roosevelt

O! throw away the worser part of it, And live the purer with the other half.

William Shakespeare

If they're running and they don't look where they're going I have to come out from somewhere and catch them.

Jerome David Salinger

O infinite virtue! com'st thou smiling from the world's great snare uncaught?

William Shakespeare

I never forget a face, but in your case I'll make an exception.

Groucho Marx

Outline

16.1 Introduction
16.2 Exception-Handling Overview
16.3 Example: Handling an Attempt to Divide by Zero
16.4 When to Use Exception Handling
16.5 Rethrowing an Exception
16.6 Exception Specifications
16.7 Processing Unexpected Exceptions
16.8 Stack Unwinding
16.9 Constructors, Destructors and Exception Handling
16.10 Exceptions and Inheritance
16.11 Processing new Failures
16.12 Class auto_ptr and Dynamic Memory Allocation
16.13 Standard Library Exception Hierarchy
16.14 Other Error-Handling Techniques
16.15 Wrap-Up