在讲新方案之前,我们先看看之前的版本都是怎样实现的
public class ExceptionDemo01 {
public static void main(String[] args) {
method();
}
public static void method() {
int x = 10;
int y = 0;
int[] arr = { 1, 2, 3 };
try {
System.out.println(a / b);
System.out.println(arr[3]);
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界");
} catch (Exception e) {
System.out.println("出问题了");
}
}
}
是不是感觉有点不够简洁,有些繁琐,所以JDK7就给出了一种新的处理方案
格式:
try{
}catch(异常名1 | 异常名2 | ...变量){
...
}
public class ExceptionDemo01 {
public static void main(String[] args) {
method();
}
public static void method() {
try {
System. out.println(a / b) ;
System. out.println(arr[3]) ;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System. out.println ("出问题了") ;
}
}
}
怎么样,是不是觉得简洁很多了。
但是,要注意,这个方法虽然简洁,但是也不是完美的:
1、处理方式是一致的。在实际开发中,很多时候可能就是要针对同类型的问题给出同一个处理,所以也是符合我们的实际开发要求的
2、多个异常间必须是平级关系。在之前的方案中,多个 catch 块要求子类异常在前,父类异常在后,也可以只用一个父类异常。但在新方案里只能是平级关系。