java异常-JDK7针对多个异常新的处理方案

在讲新方案之前,我们先看看之前的版本都是怎样实现的

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 块要求子类异常在前,父类异常在后,也可以只用一个父类异常。但在新方案里只能是平级关系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值