// ParseIntException.java // Class demo by THC to show a simple exception. import java.util.Scanner; public class ParseIntException { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { System.out.print("Enter a number: "); String s; s = input.nextLine(); int i = 0; // The following line just lets the default NumberCaughtException // occur if s contains non-digits. // i = Integer.parseInt(s); // The following lines catch the exception. try { i = parseInt(s); // remove Integer. to call the method below } catch (NumberFormatException e) { System.out.println("Caught exception: " + e.getMessage()); } System.out.println("You entered " + i); } } // We could write parseInt ourselves. public static int parseInt(String s) { int value = 0; // integer value to be returned // Go through each character of s. for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') // do we have a digit? value = (value * 10) + (c - '0'); // yes, so update value else throw new NumberFormatException(s); // no, so throw exception } return value; } }