Catching multiple exceptions in the same catch block is useful when different exceptions need to be handled in the same way. - Java Language Basics

Java examples for Language Basics:try catch finally

Description

Catching multiple exceptions in the same catch block is useful when different exceptions need to be handled in the same way.

Demo Code

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    private static final Logger logger = Logger.getLogger("log.txt");

    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        try {/* w ww.  ja  v a 2s. c  o  m*/
            Scanner scanner = new Scanner(System.in);
            int number = scanner.nextInt();
            if (number < 0) {
                throw new InvalidParameter();
            }
            System.out.println("The number is: " + number);
        } catch (InputMismatchException | InvalidParameter e) {
            logger.log(Level.INFO, "Invalid input, try again");
        }
    }
}
class InvalidParameter extends java.lang.Exception {

    public InvalidParameter() {
        super("Invalid Parameter");
    }
}

Related Tutorials