Chapter 10: Handling Exceptions


OVERVIEW

The following runtime situation exemplifies the need for exception handling in a computer program: Let's say that your program is trying to read data from a file that was accidently or otherwise deleted by some other program just moments earlier. Your program now has the following options: it could crash—with possibly disastrous consequences in real-world applications; or it could trap the error condition and take remedial measures of some sort, including seeking help from a human or some other program. Other similar situations that can lead to runtime error conditions include encountering wrong kind of data or incorrectly formated data in a file during read operations, trying to write to a file when the disk is full, trying to access an array index that is out of range, encountering excessive communication delays or disruptions in network programming, and so on.

A measure of protection against potentially error-condition producing statements in a program can be achieved by embedding such statements inside if blocks and making their execution conditional. This is commonly done in C for file I/O when we first make sure that the file pointer is not NULL before attempting any I/O operations, and when we test the error and the end-of-file indicators associated with the input and the output streams to make sure that it was not an error condition that terminated an I/O operation.

One shortcoming of error (or, in modern parlance, exception) handling by such if statements is that the decision to use them is left entirely to the discretion of a programmer. This approach to the handling of exceptions is also much too local to allow for a smooth transfer of control to a different function or even to an entirely different software module when an exception is thrown. While in C (and in C++) it is possible to achieve nonlocal transfer of control with the setjmp and longjmp macros, they are not appropriate for object-oriented programming, as we will see in this chapter.

Since it is sometimes easier to appreciate the virtues of something by examining the lack thereof in the alternatives, in this chapter we will first quickly review the setjmplongjmp mechanism of C for multilevel return and point out its shortcomings for OO. That will set us up to review the try-catch of C++ and Java for the right approach to exception handling.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net