首页 > 代码库 > try catch finally中return语句与非return语句的执行顺序问题

try catch finally中return语句与非return语句的执行顺序问题

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++x32

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 FileNotFoundExceptionthis is finally1

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 FileNotFoundExceptionthis is finally3

 

4:另外,throw语句之后不能接任何语句,unreachable。

部分摘自http://blog.csdn.net/leigt3/archive/2010/01/15/5193091.aspx

  

  

  

try catch finally中return语句与非return语句的执行顺序问题