Java Reference
In-Depth Information
from which exceptions may be thrown. It is followed by any number of catch
clauses; the code in each catch clause takes care of a particular type of exception.
In Example 1-11, there are three possible user-input errors that can prevent the
program from executing normally. Therefore, the two main lines of program code
are wrapped in a try clause followed by three catch clauses. Each clause notifies
the user about a particular error by printing an appropriate message. This example
is fairly straightforward. You may want to consult Chapter 2 of Java in a Nutshell ,
as it explains exceptions in more detail.
Example 1−11: FactComputer.java
package com.davidflanagan.examples.basics;
/**
* This program computes and displays the factorial of a number specified
* on the command line. It handles possible user input errors with try/catch.
**/
public class FactComputer {
public static void main(String[] args) {
// Try to compute a factorial.
// If something goes wrong, handle it in the catch clause below.
try {
int x = Integer.parseInt(args[0]);
System.out.println(x + "! = " + Factorial4.factorial(x));
}
// The user forgot to specify an argument.
// Thrown if args[0] is undefined.
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("You must specify an argument");
System.out.println("Usage: java FactComputer <number>");
}
// The argument is not a number. Thrown by Integer.parseInt().
catch (NumberFormatException e) {
System.out.println("The argument you specify must be an integer");
}
// The argument is < 0. Thrown by Factorial4.factorial()
catch (IllegalArgumentException e) {
// Display the message sent by the factorial() method:
System.out.println("Bad argument: " + e.getMessage());
}
}
}
Interactive Input
Example 1-12 shows yet another program for computing factorials. Unlike Exam-
ple 1-11, however, it doesn't just compute one factorial and quit. Instead, it
prompts the user to enter a number, reads that number, prints its factorial, and
then loops and asks the user to enter another number. The most interesting thing
about this example is the technique it uses to read user input from the keyboard.
It uses the readLine() method of a BufferedReader object to do this. The line that
creates the BufferedReader may look confusing. For now, take it on faith that it
works; you don't really need to understand how it works until we reach Chapter 3.
Another feature of note in Example 1-12 is the use of the equals() method of the
String object line to check whether the user has typed “quit”.
Search WWH ::




Custom Search