// This is a simple test of Exceptions. The program reads input // from the user, and prints error messages until the input is an // integer between 25 and 75 inclusive // // File: ExceptionTest.java // Author: Benjamin Lewis // Last modified: Tuesday February 23, 1999 import java.io.*; public class ExceptionTest { public static void main(String[] args) { BufferedReader instream = new BufferedReader(new InputStreamReader(System.in)); int inputInt = 0; boolean inputOK = false; System.out.println("Input an integer from 25 to 75"); while (!inputOK) { try { inputOK = true; // assume the input is ok until proven wrong System.out.print("> "); // cute little prompt inputInt = Integer.parseInt(instream.readLine()); processInput(inputInt); } catch (NumberFormatException nfe) { System.out.println("Not a valid integer!"); inputOK = false; } catch (OutOfRangeException ore) { System.out.println(ore.getMessage()); inputOK = false; } catch (IOException ioe) { // this shouldn't happen System.err.println("Uh oh, an IOException: "+ioe.getMessage()); System.exit(0); } } System.out.println("The input "+inputInt+" is valid"); } public static void processInput(int input) throws OutOfRangeException { if (input > 75) { throw new OutOfRangeException("Too High!"); } if (input < 25) { throw new OutOfRangeException("Too Low!"); } // in a real application one would actually do something with the // input here. } } // lets create our own exception to handle the out of range cases class OutOfRangeException extends Exception { public OutOfRangeException(String message) { super(message); } }