java发生异常之后的返回值

                                            java异常之返回值

java发生异常之后在try里写了返回值,在finally里也写了返回值,得到的返回值是什么呢?

package Test;

public class TestException {

	public static void main(String[] args) {
		
		System.out.println(getname());
		
	}
	public static String getname() {
		try{
			System.out.println("执行到try");
			Integer.parseInt("test");
			return "try";
		}

		catch(Exception e){
			System.out.println("执行到catch");
		        return "catch";
		}
		finally {
			System.out.println("执行到finally");
			return "finally";
		}
		
	}

}

看下输出的结果:

如果没有发生异常,在try和finally里面都写return,返回值是什么呢?

package Test;

public class TestException {

	public static void main(String[] args) {
		
		System.out.println(getname());
		
	}
	public static String getname() {
		try{
			System.out.println("执行到try");
			return "try";
		}

		catch(Exception e){
			System.out.println("执行到catch");
		}
		finally {
			System.out.println("执行到finally");
			return "finally";
		}
	}

}

你可能觉得try里面的return没有执行,那么我们这样改:

package Test;

public class TestException {

	public static void main(String[] args) {
		
		System.out.println(getname());
		
	}
	public static String getname() {
		try{
			System.out.println("执行到try");
			return "try";
		}

		catch(Exception e){
			System.out.println("执行到catch");
		}
		finally {
			System.out.println("执行到finally");
		}
		return "finally";
	}

}

我们可以看到try里面的return确实执行了。而且finally语句也执行了。函数值一旦返回不就结束这个函数的执行了么?

这个确实如此。不过在异常处理中。当try或者catch中有return后,会直接把return的语句放到finally中。而且如果

finally中如果有return,会覆盖try或者catch中的return。这是无论是否发生异常和在try,catch里写返回值之后finally都

会执行的原因。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值