在Java7之前,每个catch块只能捕获一种类型的异常,但从Java7开始一个catch可以捕获多种类型的异常。
使用一个catch块捕获多种类型的异常时需要注意如下两个地方:
1>捕获多种类型的异常时,多种异常类型之间用竖线(|)隔开。
2>捕获多种类型的异常时,异常变量有隐式的final修饰,因此程序不能对异常变量重新赋值。
示例:
public class MultiExceptionTest{
public static void main(String[ ] args){
try{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("输入两数相除结果:" + c);
}catch(IndexOutOfBoundsException | NumberFormatException | ArithemticException ie){//(1)
System.out.println(“程序发生了数组越界、数字格式异常、算数异常之一”);
//捕获多异常时,异常变量默认有final修饰
//所以下面代码有错
ie = new ArithmeticException("test");//(2)
}catch(Exception e){
System.out.println("未知异常");
//捕获一种类型的未知异常时,异常变量没有final修饰
//所以下面代码完全正确
e = new RuntimeException("test");//(3)
}
}
}
上面程序中1处使用了IndexOutOfBoundsException | NumberFormatException | ArithemticException来定义异常类型,这就表明该catch块可以同时捕获这三种类型的异常。捕获多种类型的异常时,异常变量使用隐式的final修饰,因此上边的2处代码会产生编译错误;捕获一种类型的异常时,异常变量没有final修饰,因此上面程序中3处代码完全正确。
最后
以上就是唠叨黄蜂最近收集整理的关于异常之Java7捕获多种类型异常的全部内容,更多相关异常之Java7捕获多种类型异常内容请搜索靠谱客的其他文章。
发表评论 取消回复