小疯以前遇到一个问题,就是关于return和finally的执行顺序问题,其实关于这个问题小疯许久以前在一篇博客中看到了解答,不过因为时间间隔找不到了,因此小疯今天在这里记录一下:java
执行顺序是:先try 如有异常就catch,而后finally,以后执行catch中的return,若是finally中也有return,那么久直接出去不执行catch中的return。code
一、finally中也有return语句以下:博客
public class TryTest { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(TryTest.test()); } public static String test() { try { System.out.println("try"); throw new Exception(); } catch(Exception e) { System.out.println("catch"); return "return"; } finally { System.out.println("finally"); return "return in finally"; } } }
执行结果以下:io
tryclass
catchtest
finally异常
return in finallystatic
可见顺序是先执行try中的输出语句而后在异常处调到catch语块,而后执行到catch中的return处没有执行return而是跳转到finally中执行。时间
二、finally中没有return语句:co
public class TryTest { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(TryTest.test()); } public static String test() { try { System.out.println("try"); throw new Exception(); } catch(Exception e) { System.out.println("catch"); return "return"; } finally { System.out.println("finally"); //return "return in finally"; } } }
执行结果以下:
try
catch
finally
return
可见执行顺序是先执行try中的输出语句而后在异常处调到catch语块,而后执行过catch的输出语句跳转到finally中执行以后返回到catch中的return语句。