BIG C++
Cay Horstmann & Timothy Budd

Laboratory Notebook
Chapter 19 – Exception Handling


Your name:

Your email address:

Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with

        exceptional conditions that may arise within a program

        making your programs more reliable and robust by dealing with exceptional conditions

        using a variety of mechanisms to handle exceptional conditions

        using try blocks and catch handlers in your own programs


P1. Lottery Numbers

This chapter focuses on the topics of error detection and error handling. To begin this lab, suppose you are part of an agency whose purpose is to monitor the results of your local lottery drawings to ensure the fairness and randomness of the drawings. For this problem, you are provided with a text file of the lottery results for each drawing. Each line, corresponding to a single drawing, contains five numbers. Each number is separated by a space. See the provided text file before you begin writing your code.

First, write a simple class called LotteryDrawing that represents a single lottery drawing. The class should store a vector of integers representing the drawn numbers. The class definition is provided below.

Lottery Text File

class LotteryDrawing

{

public:

LotteryDrawing(const vector<int>& input);

void printDrawing();

private:

vector<int> numbers;

};

Provide implementation for the constructor shown. Also, provide implementation for the printDrawing() function such that it displays the five numbers on a single line on the console.

Submit all of the code for your answer in the space below.


R1. Handling Exceptional Situations

The function below computes sales tax owed on a certain purchase. An error situation should occur whenever the user passes a negative price or negative sales tax into the function. In this review problem, you will modify the function such that the erroneous input is handled in three different ways. Thus, you will familiarize yourself with some of the different ways that errors are typically handled in programming applications. You will later apply one of these techniques to the lottery scenario described in Problem P1.

double getSalesTax(double price, double taxRate = 0.625)

{

return price * taxRate;

}

 

In the space below, modify the function such that it outputs a special value in the case that one or both inputs are invalid. What value did you choose and why?

In the space below, modify the function such that it prints out an error message and causes the program to immediately exit in the case that one or both of the inputs are invalid.

In the space below, modify the function such that it throws an object of type InvalidInputException in the case that either one or both inputs are invalid. Do not bother implementing this object.


P2. Utility Functions

Returning to the lottery problem, your next job is to write an additional class called LotteryReader. The first function listed within this class, called readDrawing(), should read a single line of lottery numbers from a file and return the numbers within a vector. Next, using the readDrawing() function just created, write a function called createLotteryHistory() that reads every entry in the file and uses that information to create a vector of LotteryDrawing objects. The class definition for this problem is provided below. The constructor should be used to initialize two private member variables. One of the variables will allow the lottery reader to know the number of individual numbers drawn per game. The other allows the reader to know the maximum number allowed for an individually drawn number.

Class LotteryReader

{

LotteryReader(int inumbersPerDrawing);

vector<int> readDrawing(ifstream* input);

vector<LotteryDrawing> createLotteryHistory(string filename);

private:

int numbersPerDrawing;

int maxNumber;

};

Provide all code in the space below.


R2. Exceptions

R1 already introduced you to exceptions. The C++ exception mechanism is often used for handling errors that occur within a program. There are several syntax issues associated with the C++ exception mechanism. In this problem, you will practice using these concepts before applying them to the more complicated lottery problem. Supply code for the computeAge() function below such that an exception of type InvalidInputException is thrown whenever either of the two inputs is negative or if the current year is less than the date of birth.

int computeAge(int currentYear, int birthDate)

{

return currentYearbirthDate;

}

Implement a main function in the space below such that, enclosed within a try statement, the computeAge() function is executed with invalid inputs. A catch statement should catch the exception, print out an error message, and cause the program to immediately exit.

Finally, define and implement the InvalidInputException class such that it stores a single text error message initialized by the class’s constructor.


P3. Creating a Working Program

 

Now that you have created the code for P1 and P2, you can assemble it together into a working program. Construct a main() function that prompts the user for the name of a file. Upon the user’s entry, the program should construct the vector of LotteryDrawing objects and print each drawing to the screen.


R3. What Should You Throw?

 

In a throw statement, you specify the item that you are throwing. Therefore, you have a choice between throwing a pointer to an object and throwing the object itself. In the space provided, rewrite the readDrawing() function such that it throws a BadDrawingException object in the case of an error. For now, assume an error occurs only when a number read from the specified file is negative. Do not yet implement this exception class.

In the space provided, rewrite the readDrawing() function such that it throws a pointer to a BadDrawingException object in the case of an error. For now, assume an error occurs only when a number read from the specified file is negative. Do not yet implement this exception class.


P4. Dealing with Errors

Now that you have the fully-functional program from P3 and practice handling errors from the review problems, you will make your lottery application more robust by handling some exceptional situations. First, you will design a BadDrawingException class from which other, more specific, exceptions classes may be derived. Add whatever features to these classes that you deem necessary. Second, redesign your readDrawing() function such that it throws a different exception whenever it encounters a type of bad entry within the file. A bad entry will be defined as one in which any of the following occurs:

 

1.      There are less than five numbers on a line.

2.      There are more than five numbers on a line.

3.      Any number encountered is negative or zero.

4.      Any number encountered is greater than 50.

5.      There are duplicate numbers existing on each line.

 

Each of the above types of errors should have its own exception class derived from the BadDrawingException class.

 

Define and implement the exception class corresponding to error type one below.

 

 

Define and implement the exception class corresponding to error type two below.

 

 

Define and implement the exception class corresponding to error type three below.

 

 

Define and implement the exception class corresponding to error type four below.

 

 

Define and implement the exception class corresponding to error type five below.

 

 

Finally, modify the readDrawing() class such that it throws the correct exception type, upon encountering an exception, in the space below. This task should be relatively easy as it is an extension to R3.

 

 

Did you choose to have your BadDrawingException base class derive any of its functionality from a standard exception class? Why or why not?

 

 


R4. Missed the Throw

Run the program written thus far and modify the input file such that an invalid entry is present. The readDrawing() function will throw an exception. Record the output of the program in the space below.

Why did you get this output?


P5. Catch It

Now that you have observed what happens whenever a program throws an object that is not caught, rewrite your createLotteryHistory() function such that it catches all possible exceptions from the readDrawing() function. Upon encountering an exception, the createLotteryHistory() function should catch it, close the file, and re-throw the exception. Provide your code in the space below.


Do not forget to send your answers when you are finished.