MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

23: Exception handling

Improved error recovery is one of the most powerful ways you can increase the robustness of your code.

show how you can make several function calls with only one catch, thus greatly reducing the amount of error-handling code you must write.

Unfortunately, it’s almost accepted practice to ignore error conditions, as if we’re in a state of denial about errors. Some of the reason is no doubt the tediousness and code bloat of checking for many errors. For example, printf( ) returns the number of arguments that were successfully printed, but virtually no one checks this value. The proliferation of code alone would be disgusting, not to mention the difficulty it would add in reading the code.

The problem with C’s approach to error handling could be thought of as one of coupling – the user of a function must tie the error-handling code so closely to that function that it becomes too ungainly and awkward to use.

One of the major features in C++ is exception handling , which is a better way of thinking about and handling errors. With exception handling,

  1. Error-handling code is not nearly so tedious to write, and it doesn't become mixed up with your "normal" code. You write the code you want to happen; later in a separate section you write the code to cope with the problems. If you make multiple calls to a function, you handle the errors from that function once, in one place.
  2. Errors cannot be ignored. If a function needs to send an error message to the caller of that function, it “throws” an object representing that error out of the function. If the caller doesn’t “catch” the error and handle it, it goes to the next enclosing scope, and so on until someone catches the error.
This chapter examines C’s approach to error handling (such as it is), why it did not work very well for C, and why it won’t work at all for C++. Then you’ll learn about try, throw, and catch, the C++ keywords that support exception handling.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru