Page 630 - Introduction to Programming with Java: A Problem Solving Approach
P. 630
596
Chapter 14 Exception Handling
5. 6.
} // end Division2 class
a) First, rewrite the program so that it still employs a double numerator and int denominator, but if the value input for the denominator is zero, it refuses to perform the division operation, and keeps asking for the denominator until the user supplies something other than zero.
b) Next, rewrite the program of part a so that if the user inputs an improper format for either numerator
or denominator, the entire input query repeats until both formats are OK. Hint: Put try and catch blocks in a loop that executes while (OK == false), and set OK = true after all of the criti- cal operations in the try block have succeeded. Note: If the scanned format is bad, you’ll get infinite looping unless you re-instantiate stdIn in each iteration, or use a two-step operation for each input (input a string and then parse it).
[after §14.7] What happens if an unchecked exception is thrown and never caught?
[after §14.9] WebPageReader program:
}
double n;
int d;
System.out.print("Enter numerator: ");
n = stdIn.nextDouble();
System.out.print("Enter divisor: ");
d = stdIn.nextInt();
System.out.println(n / d);
// end main
In addition to testing your exception handling prowess, this exercise also tests your ability to use online help and/or reference books. The following program attempts to read in a Web address and print the
contents of the Web page at that address. In the given program:
Apago PDF Enhancer
For each class that’s used, add an import statement for it, if it’s necessary.
For each method call and constructor call:
If it throws an unchecked exception, ignore it. If it throws a checked exception:
Specify the specific exception in a throws clause.
Within a catch block in main, catch the exception and print the exception’s message using its getMessage method.
Assume that the following code works except for the items mentioned above.
/*************************************************************
*
WebPageReader.java
Dean & Dean
This reads a Web page.
*************************************************************/
*
*
*
import java.util.Scanner;
public class WebPageReader
{
BufferedReader reader;
public WebPageReader(String webAddress)
{