1.11 Handling Exceptions

Example 1-11 shows a program that uses the Integer.parseInt( ) method to convert a string specified on the command line to a number. The program then computes and prints the factorial of that number, using the Factorial4.factorial( ) method defined in Example 1-10. That much is simple; it takes only two lines of code. The rest of the example is concerned with exception handling, or, in other words, taking care of all of the things that can go wrong. You use the try/catch statement in Java for exception handling. The try clause encloses a block of code 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 je3.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( ));         }     } }


Java Examples in a Nutshell
Java Examples in a Nutshell, 3rd Edition
ISBN: 0596006209
EAN: 2147483647
Year: 2003
Pages: 285

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net