Catch multiple exception types to improve type checking in Java
Description
The following code shows how to catch multiple exception types to improve type checking.
Example
/* ww w . java2 s . co m*/
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
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");
}
}
The code above generates the following result.