当需要以相同的方式处理不同的异常时,在同一catch块中捕获多个异常非常有用。
import java.util.InputMismatchException; import java.util.Scanner; import java.util.logging.Level;// from 时代Java - nowjava.com 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 { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt();/* 来 自 n o w j a v a . c o m - 时 代 Java*/ 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"); } }