Sample Program - Using Exceptions to Validate Input

//  this program contains a loop that will read a valid integer
//  in the loop a line of input is read and parsed into an int variable
//  if the parsing works a flag is set and the loop will be terminated
//  if the parsing doesn't work, the catch block prints an error message
//  and the loop will continue

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class ValidInput {
   public static void main(String args[]) {
      InputStreamReader convert = new InputStreamReader(System.in);
      BufferedReader stdin = new BufferedReader(convert);
      int num = 0;
      String instr = null;
      boolean ok = false;

//  keep reading until a valid int is read

      do {
         try {
            System.out.print("Enter an integer: ");
            instr = stdin.readLine();
            num = Integer.parseInt(instr);

//  ok is changed only if parseInt didn't throw an exception

            ok = true;
         }

//  print a message if the value entered was not an int

         catch (NumberFormatException e) {
            System.out.println("Error, invalid value '" + instr + "' entered.");
         }

//  print a message and exit if an I/O error occurred

         catch (IOException e) {
            System.out.println("Error occurred while reading. Exiting...");
            System.exit(1);
         }
      }
      while (!ok);
      System.out.println("Valid value entered was: " + num);
   }
}

Output
Enter an integer: yes
Error, invalid value 'yes' entered.
Enter an integer: no
Error, invalid value 'no' entered.
Enter an integer: a
Error, invalid value 'a' entered.
Enter an integer: 55
Valid value entered was: 55


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page