IO流_try...catch的方式处理异常2

101 篇文章 0 订阅
15 篇文章 0 订阅
package cn.itcast_02;

/*
 * A:一个异常 
 * B:两异常的处理
 * 		a:每一个写一个tcy...catch
 * 		b:写一个try,多个catch
 * 			try{
 * 				...
 * 			}catch(异常类名 变量名){
 * 				...
 * 			}catch(异常类名 变量名){
 * 				...
 * 			}
 * 			...
 * 
 * 			注意事项:
 * 				1.能明确的尽量明确,不要用大的来处理。
 * 				2.平级关系的异常谁前谁后无所谓,如果出现了子父关系,父必须在后面。
 * 注意:
 * 		一旦tcy里面出了问题,就会在这里把问题给抛出去,然后和catch里面的问题进行匹配,
 * 		一旦有匹配的,就执行catch里面的处理,然后结束了tcy...catch
 * 		继续执行后面的语句。
 */
public class ExceptionDemo2 {
	public static void main(String[] args) {
		// method1();

		// method2();

		// method3();

		method4();
	}

	public static void method4() {
		int a = 10;
		int b = 0;
		int[] arr = { 1, 2, 3 };

		// Exception在后面
		try {
			System.out.println(arr[3]);
			System.out.println(a / b);
		} catch (ArithmeticException e) {
			System.out.println("除数不能为0");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("数据越界");
		} catch (Exception e) {
			System.out.println("有问题");
		}

		// Exception在前面是不可以的
		// try {
		// System.out.println(arr[3]);
		// System.out.println(a / b);
		// } catch (Exception e) {
		// System.out.println("有问题");
		// } catch (ArithmeticException e) {
		// System.out.println("除数不能为0");
		// } catch (ArrayIndexOutOfBoundsException e) {
		// System.out.println("数据越界");
		// }

		System.out.println("over");
	}

	// 两个异常的处理
	public static void method3() {
		int a = 10;
		int b = 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("数据越界");
		}

		System.out.println("over");
	}

	// 两个异常
	public static void method2() {
		int a = 10;
		int b = 0;
		try {
			System.out.println(a / b);
		} catch (ArithmeticException e) {
			System.out.println("除数不能为0");
		}
		int[] arr = { 1, 2, 3 };

		try {
			System.out.println(arr[3]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("数据越界");
		}
		System.out.println("over");
	}

	// 一个异常
	public static void method1() {
		int a = 10;
		int b = 0;
		// System.out.println(a / b);
		try {
			System.out.println(a / b);
		} catch (ArithmeticException ae) {
			System.out.println("除数不能为零");
		}
		System.out.println("over");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值