📅  最后修改于: 2020-04-05 07:15:48             🧑  作者: Mango
// Java展示在Java7之前,我们必须在每个catch块中仅捕获一种异常类型
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " 是99的因子");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}
输入1:
芒果文档
输出2:
Exception encountered java.lang.NumberFormatException:
For input string: "芒果文档"
输入2:
0
输出2:
Arithmetic Exception encountered java.lang.ArithmeticException: / by zero
从Java 7.0开始,单个catch块可以通过用|分隔每个异常来捕获多个异常。
// Java展示多捕获multicatch
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " 是99的因子");
}
catch (NumberFormatException | ArithmeticException ex)
{
System.out.println("Exception encountered " + ex);
}
}
}
输入1:
芒果文档
输出1:
Exception encountered java.lang.NumberFormatException:
For input string: "芒果文档"
输入2:
0
输出2:
Exception encountered
java.lang.ArithmeticException: / by zero
一个处理多个异常类型的catch块不会在编译器生成的字节码中创建任何重复项,也就是说,该字节码不具有异常处理程序的复制项。
重要事项:
// 下面不合法,因为Exception是NumberFormatException的祖先
catch(NumberFormatException | Exception ex)