1 import java.util.InputMismatchException;
2 import java.util.NoSuchElementException;
3 import java.util.Scanner;
4
5 public class ExceptionDemo
6 {
7 public static void main(String[] args)
8 {
9 String inputValues = "two 42 43 three 44 ";
10 // This scanner reads the values from the given string.
11 Scanner in = new Scanner(inputValues);
12 boolean done = false;
13 while (!done)
14 {
15 try
16 {
17 int n = in.nextInt();
18 System.out.println("Read integer " + n);
19 if (n == 42) { throw new IllegalArgumentException("Ugh! 42"); }
20 String str = in.next();
21 System.out.println("Read string " + str);
22 n = Integer.parseInt(str);
23 System.out.println("Parsed integer " + n);
24 }
25 catch (NumberFormatException ex)
26 {
27 System.out.println(ex.getMessage());
28 }
29 catch (IllegalArgumentException ex)
30 {
31 System.out.println(ex.getMessage());
32 }
33 catch (InputMismatchException ex)
34 {
35 // We "fix" the problem by removing the offending input
36 System.out.println("Removing " + in.next());
37 }
38 catch (NoSuchElementException ex) // This happens at the end of the input
39 {
40 ex.printStackTrace();
41 System.out.println("Terminating the loop.");
42 done = true;
43 }
44 }
45 }
46 }