Finally关键字和return的研究

来源:互联网 发布:万网域名证书查询 编辑:程序博客网 时间:2024/06/13 08:35

  今天在帮朋友整理面试总结的时候,遇到一个关于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)