标签:style blog http color java io ar 问题 div
finally语句一定是会被执行的,不管前边的try块catch块中有无return语句,并且如果finally中存在return语句,这个return语句将会是最后执行的return语句,即函数最后的返回值。try,catch中的return并不是让函数直接返回,而是return语句执行完毕,把返回结果放到函数栈中,转而执行finally块,所以,若是finally中含有return语句,那么函数栈中的返回值将被刷新。看以下几种情况:
1:try有return,finally无
public class TryFinallyReturnTest {
static int test(){
int x=1;
try {
++x;
return x;
} catch (Exception e) {
// TODO: handle exception
}finally{
++x;
System.out.println("finally++x"+x);
}
return 0;
}
public static void main(String[] args) {
System.out.println(new TryFinallyReturnTest().test());
}
}
输出结果:
finally++x3 2
2:当 try 中抛出异常且 catch 中有 return 语句, finally 中没有 return 语句, java 先执行 catch 中非 return 语句,再执行 finally 语句,最后执行 catch 中 return 语句。
public class Test {
public int testTry(){
FileInputStream fi=null;
try{
fi=new FileInputStream("");
}catch(FileNotFoundException fnfe){
System.out.println("this is FileNotFoundException");
return 1;
}catch(SecurityException se){
System.out.println("this is SecurityException");
}finally{
System.out.println("this is finally");
}
return 0;
}
public static void main(String[] args) {
Test t= new Test();
System. out .println(t.testTry());
}
}
Output :
this is FileNotFoundException
this is finally
1
3:当 try 中抛出异常且 catch 中有 return 语句, finally 中也有 return 语句, java 先执行 catch 中非 return 语句,再执行 finally 中非 return 语句,最后执行 finally 中 return 语句,函数返回值为 finally 中返回的值。
public class Test {
public int testTry(){
FileInputStream fi=null;
try{
fi=new FileInputStream("");
}catch(FileNotFoundException fnfe){
System.out.println("this is FileNotFoundException");
return 1;
}catch(SecurityException se){
System.out.println("this is SecurityException");
}finally{
System.out.println("this is finally");
return 3;
}
//return 0;
}
public static void main(String[] args) {
Test t= new Test();
System. out .println(t.testTry());
}
}
Output :
this is FileNotFoundException
this is finally
3
4:另外,throw语句之后不能接任何语句,unreachable。
部分摘自http://blog.csdn.net/leigt3/archive/2010/01/15/5193091.aspx
try catch finally中return语句与非return语句的执行顺序问题
标签:style blog http color java io ar 问题 div
原文地址:http://www.cnblogs.com/sungyouyu/p/3931545.html