11. Write a function with an exception specification that can throw four exception types: a char, an int, a bool, and your own exception class. Catch each in main( ) and verify the catch. Derive your exception class from a standard exception. Write the function in such a way that the system recovers and tries to execute it again.
12. Modify your solution to the exercise 8 to throw a double from the function, violating the exception specification. Catch the violation with your own unexpected handler that displays a message and exits the program gracefully (meaning abort( ) is not called).
13. Write a Garage class that has a Car that is having troubles with its Motor. Use a function-level try block in the Garage class constructor to catch an exception (thrown from the Motor class) when its Car object is initialized. Throw a different exception from the body of the Garage constructor’s handler and catch it in main( ).
2: Defensive programming
Writing "perfect software" may be an elusive Holy Grail for developers, but a few defensive techniques, routinely applied, can go a long way toward narrowing the gap between code and ideal.
Although the complexity of typical production software guarantees that testers will always have a job, chances are you still yearn to produce defect-free software. (At least we hope you do!) Object-oriented design techniques do much to corral the difficulty of large projects, to be sure. Eventually, however, you have to get down to writing loops and functions. These details of "programming in the small" become the building blocks of the implementation of larger components called for by your design efforts. If your loops are off by one or your functions calculate the correct values only "most" of the time, you’re in deep trouble no matter how fancy your overall methodology. In this chapter, we’re interested in coding practices that keep you on track toward a working solution regardless of the size of your project.
Your code is, among other things, an expression of your attempt to solve a problem. It should be clear to the reader (including yourself) exactly what you were thinking when you designed that loop. At certain points in your program, you should be able to make bold statements that some condition or other holds. (If you can’t, you really haven’t yet solved the problem.) Such statements are called invariants, since they should invariably be true at the point where they appear in the code; if not, either your design is faulty, or your code does not accurately reflect your design. (In other words, you’ve got bugs!).
To illustrate, consider how to write a program that plays the guessing game of Hi-lo. You play this game by having one person think of a number between 1 and 100, and having the other person guess the number. (We’ll let the computer do the guessing.) The person who holds the number tells the guesser whether their guess is high, low or correct. The best strategy for the guesser is of course binary search, which chooses the midpoint of the range of numbers where the sought-after number resides. The high-low response tells the guesser which half of the list holds the number, and the process repeats, halving the size of the active search range on each iteration. So how do you write a loop to drive the repetition properly? It’s not sufficient to just say.
bool guessed = false;
while (!guessed) {
…
}
because a malicious user might respond deceitfully, and you could spend all day guessing. What assumption, however simple, are you making each time you guess? In other words, what condition should hold by design on each loop iteration?.
The simple assumption we’re after is, of course, that the secret number is within the current active range of unguessed numbers, beginning with the range [1, 100]. Suppose we label the endpoints of the range with the variables low and high. Each time you pass through the loop you need to make sure that if the number was in the range [low, high] at the beginning of the loop, you calculate the new range so that it still contains the number at the end of the current loop iteration.
The goal is to express the loop invariant in code so that a violation can be detected at runtime. Unfortunately, since the computer doesn’t know the secret number, you can’t express this condition directly in code, but you can at least make a comment to that effect:
while (!guessed) {
// INVARIANT: the number is in the range [low, high]
…
}
If we were to stop this thread of discussion right here, we would have accomplished a great deal if it helps clarify how you design loops. Fortunately, we can do better than that. What happens when the user says that a guess is too high when it isn’t or that it’s too low when it in fact is not? The deception will in effect exclude the secret number from the new subrange. Because one lie always leads to another, eventually your range will diminish to nothing (since you shrink it by half each time and the secret number isn’t in there). We can easily express this condition concretely, as the following program illustrates.
//: C02:HiLo.cpp
// Plays the game of Hi-lo to illustrate a loop invariant
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Think of a number between 1 and 100\n";
cout << "I will make a guess; ";
cout << "tell me if I'm (H)igh or (L)ow\n";
int low = 1, high = 100;
bool guessed = false;
while (!guessed) {
// Invariant: the number is in the range [low, high]
if (low > high) { // Invariant violation
cout << "You cheated! I quit\n";
return EXIT_FAILURE;
}
int guess = (low + high) / 2;
cout << "My guess is " << guess << ". ";
cout << "(H)igh, (L)ow, or (E)qual? ";
string response;
cin >> response;
switch(toupper(response[0])) {
case 'H':
high = guess - 1;
break;
case 'L':
low = guess + 1;
break;
case 'E':
guessed = true;
break;
default:
cout << "Invalid response\n";
continue;
}
}
cout << "I got it!\n";
return EXIT_SUCCESS;
} ///:~
The violation of the invariant is easily detected with the condition if (low > high), because if the user always tells the truth, we will always find the secret number before we run out of numbers to guess from. (See the last paragraph of the text that follows the program extractCode.cpp at the end of Chapter 3 for an explanation of the macros EXIT_FAILURE and EXIT_SUCCESS).