Finally关键字和return的研究

  今天在帮朋友整理面试总结的时候,遇到一个关于Finally关键字和return的问题,所以我用代码研究了一下:

一共研究了5种情况

package rrr;
public class Fytest {
public int test(String string){
int b=0;
try {
//这里的a为了实现抛异常
int a=Integer.valueOf(string);
b++;
System.out.println("try块里的b的值"+b);
return b;
} catch (Exception e) {
throw new RuntimeException("类转化异常");
}finally {
b++;
System.out.println("finally块里的b的值"+b);
return b;
}


}
public static void main(String[] args) {
Fytest fytest=new Fytest();
int num=fytest.test("0");
System.out.println("最后返回的值"+num);
}
}

第一种(try和finally中有return)——try块里的b的值1,finally块里的b的值2,最后返回的值2

——————————————————————

public int test(String string){
int b=0;
try {
//这里的a为了实现抛异常
int a=Integer.valueOf(string);
b++;
System.out.println("try块里的b的值"+b);
//return b;
} catch (Exception e) {
throw new RuntimeException("类转化异常");
}finally {
b++;
System.out.println("finally块里的b的值"+b);
return b;
}
}

第二种(finally中有return)——try块里的b的值1,finally块里的b的值2,最后返回的值2

————————————————————————

public int test(String string){
int b=0;
try {
//这里的a为了实现抛异常
int a=Integer.valueOf(string);
b++;
System.out.println("try块里的b的值"+b);
return b;
} catch (Exception e) {
throw new RuntimeException("类转化异常");
}finally {
b++;
System.out.println("finally块里的b的值"+b);
//return b;
}
}

第三种(try中有return)——try块里的b的值1,finally块里的b的值2,最后返回的值1

————————————————————————

package rrr;
public class Fytest {
public int test(String string){
int b=0;
try {
//这里的a为了实现抛异常
int a=Integer.valueOf(string);
b++;
System.out.println("try块里的b的值"+b);
//return b;
} catch (Exception e) {
throw new RuntimeException("类转化异常");
}finally {
b++;
System.out.println("finally块里的b的值"+b);
return b;
}
}

public static void main(String[] args) {
Fytest fytest=new Fytest();
int num=fytest.test("s");
System.out.println("最后返回的值"+num);
}
}

第四种(这次走catch块,finally中有return)——finally块里的b的值1,最后返回的值1

————————————————————————

public int test(String string){
int b=0;
try {
//这里的a为了实现抛异常
int a=Integer.valueOf(string);
b++;
System.out.println("try块里的b的值"+b);
return b;
} catch (Exception e) {
throw new RuntimeException("类转化异常");
}finally {
b++;
System.out.println("finally块里的b的值"+b);
//return b;
}
}

第五种(这次走catch块,try中有return)——finally块里的b的值1
Exception in thread "main" java.lang.RuntimeException: 类转化异常
at rrr.Fytest.test(Fytest.java:14)
at rrr.Fytest.main(Fytest.java:24)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值