Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

1: Exception Handling

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

Unfortunately, it s almost accepted practice to ignore error conditions, as if we re in a state of denial about errors. One reason, no doubt, is the tediousness and code bloat of checking for many errors. For example, printf( ) returns the number of characters 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 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 dynamic scope, and so on until the error is either caught or the program terminates because there was no handler to catch that type of exception.

This chapter examines C s approach to error handling (such as it is), discusses why it did not work well for C, and explains why it won t work at all for C++. This chapter also covers try, throw, and catch, the C++ keywords that support exception handling.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire