Catching multiple exception types to improve type checking : Exception Catch « JDK 7 « Java






Catching multiple exception types to improve type checking


import java.util.InputMismatchException;
import java.util.Scanner;

public class Test {
  public static void main(String[] args) {
    try {
      System.out.print("Enter a number: ");
      int number = new Scanner(System.in).nextInt();
      if (number < 0) {
        throw new InvalidParameter();
      }
      System.out.println("The number is: " + number);
    } catch (InputMismatchException | InvalidParameter e) {
      System.out.println("Invalid input, try again");
    }
  }
}

class InvalidParameter extends java.lang.Exception {
  public InvalidParameter() {
    super("Invalid Parameter");
  }
}

 








Related examples in the same category

1.Catching Multiple Exception Types To Improve Type Handling