Handling Errors and Exceptions 717
20
Exceptional Circumstances ............................................................................
You can’t eliminate exceptional circumstances; you can only prepare for them. What
happens if your program requests memory to dynamically allocate an object, and there
isn’t any available? How will your program respond? Or, what will your program do if
you cause one of the most common math errors by dividing by zero? Your choices
include
- Crash.
- Inform the user and exit gracefully.
- Inform the user and allow the user to try to recover and continue.
- Take corrective action and continue without disturbing the user.
Consider Listing 20.1, which is extremely simple and ready to crash; however, it illus-
trates a problem that makes it into many programs and that is extremely serious!
LISTING20.1 Creating an Exceptional Situation
0: // This program will crash
1: #include <iostream>
2: using namespace std;
3:
4: const int DefaultSize = 10;
5:
6: int main()
7: {
8: int top = 90;
9: int bottom = 0;
10:
11: cout << “top / 2 = “ << (top/ 2) << endl;
12:
13: cout << “top divided by bottom = “;
14: cout << (top / bottom) << endl;
15:
16: cout << “top / 3 = “ << (top/ 3) << endl;
17:
18: cout << “Done.” << endl;
19: return 0;
20: }
top / 2 = 45
OUTPUT top divided by bottom =