JavaSe笔记关于异常处理

默认执行try中内容, 如果try中没有异常抛出,则执行finally内容,最后则会执行 方法尾部内容。

public void test(){
    try {
    System.out.println("try");
    return;
    } catch(Exception e){
    System.out.println("catch");
    }finally {
    System.out.println("finally");
    }
    System.out.println("out");
}

输出内容为try-finally-out.


如果try中抛出了异常 ,但catch中没有设定catch或者设定的捕获异常与抛出的异常不同从而无法捕获到,则执行顺序为 try到触发异常位置,然后进入finlly,此时不会执行out的内容;

	public  void test() {
			try {
				int num1 = 2;		int num2 = 0;
				int result = num1 / num2;
				//System.out.println(result);
				//throw new NumberFormatException( );
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.print("1");
			} catch (NumberFormatException e) {
				System.out.print("2");
			} finally {
				System.out.print("4");
			}
			System.out.print("5");
	}

 

输出为4


发出的异常被捕获到,则执行顺序为,try-》触发异常未知,catch捕获异常,finally代码块,方法尾部代码块

	public  void test() {
			try {
				int num1 = 2;		int num2 = 0;
				//int result = num1 / num2;
				//System.out.println(result);
				throw new NumberFormatException( );
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.print("1");
			} catch (NumberFormatException e) {
				System.out.print("2");
			} finally {
				System.out.print("4");
			}
			System.out.print("5");
	}

输出结果为245

 

throw 是抛出异常,用在代码块中(一般在try块中用来被catch捕获) 如  throw new Exception();

throws 是将异常处理交给上一级处理,用在函数后面,如 public void test() throws Excetion;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值