The exception and bad_exception Classes. McGraw-Hill The Complete Reference Fourth Edition
Annonce
Annonce
506
C + + : T h e C o m p l e t e R e f e r e n c e
The exception and bad_exception Classes
When a function supplied by the C++ standard library throws an exception, it will be an object derived from the base class exception. An object of the class bad_exception can be thrown by the unexpected handler. These classes require the header <exception>.
Applying Exception Handling
Exception handling is designed to provide a structured means by which your program can handle abnormal events. This implies that the error handler must do something rational when an error occurs. For example, consider the following simple program. It inputs two numbers and divides the first by the second. It uses exception handling to manage a divide-by-zero error.
#include <iostream> using namespace std; void divide(double a, double b); int main()
{ double i, j; do { cout << "Enter numerator (0 to stop): "; cin >> i; cout << "Enter denominator: "; cin >> j; divide(i, j);
} while(i != 0);
} return 0; void divide(double a, double b)
{ try { if(!b) throw b; // check for divide-by-zero cout << "Result: " << a/b << endl;
} catch (double b) { cout << "Can't divide by zero.\n";
C h a p t e r 1 9 : E x c e p t i o n H a n d l i n g
507
}
}
While the preceding program is a very simple example, it does illustrate the essential nature of exception handling. Since division by zero is illegal, the program cannot continue if a zero is entered for the second number. In this case, the exception is handled by not performing the division (which would have caused abnormal program termination) and notifying the user of the error. The program then reprompts the user for two more numbers. Thus, the error has been handled in an orderly fashion and the user may continue on with the program. The same basic concepts will apply to more complex applications of exception handling.
Exception handling is especially useful for exiting from a deeply nested set of routines when a catastrophic error occurs. In this regard, C++'s exception handling is designed to replace the rather clumsy C-based setjmp( ) and longjmp( ) functions.
Remember, the key point about using exception handling is to provide an orderly way of handling errors. This means rectifying the situation, if possible.
This page intentionally left blank
Chapter 20
The C++ I/O
System Basics
509
Copyright © 2003 by The McGraw-Hill Companies. Click here for terms of use.
Download
Annonce