## CS 1401, Quiz 13, Solutions

Date: Tuesday, April 24, 2007
Name (please type legibly, ideally in block letters): ______________________________________________________________________
Class section (9:00 am or 10:30 am):_______________________________

1. Suppose that in a program, at some point, we compute the percentage of female students in a CS class as follows:

```percentage = female / (female + male);
```
where all three variables percentage, female, and male are of integer type. In this code, if we accidentally left both male and female to be 0, the program will interrupt its computations and produce a (not necessarily clear) error message.

Modify this part of your program in such a way that if both values are zeros (i.e., if the program attempts to divide by 0), it will produce a meaningful error message which will be very clear to the user.

```
Solution:

try{
percentage = female / (female + male);
}
catch(ArithmeticException e){
System.out.println("It looks like you forgot to enter numbers of " +
"male and female students, because both values are now 0.");
}

```
2. If the variables male and female are of type double, then there will be no interruption, division of 0 by 0 will return NaN (not a number). Modify your exceptions code from Problem 1 in such a way that your program will produce a meaningful error message for variables of type double.

```
Solution:

try{
percentage = female / (female + male);
if (female + male == 0.0)
throw new Exception("It looks like you forgot to enter numbers of " +
"male and female students, because both values are now 0.");
}
catch(Exception e){
System.out.println(e.getMessage()):
}

```