ITeye博客

不能在finally块中return

shawnccx · 2010-08-13 15:59 · 编程语言 · F# · Markdown

【现象描述】

try-catch块中永远返回finally中return的值 【错误代码】

static boolean f() { try { return true; } finally { return false; } } 错误分析 在这个应用场景中,不要用return来退出finally语句块,因为finally语句块都会被执行到,这样try程序块中执行正常也会在finally中退出,不会再回到try程序块中。

Try-catch的流程说明:

try { … … return true; }catch(异常){
… } finally { … } } 1,try-catch-finally,

如果try语句块遇到异常,try下面的代码就不执行了,转而执行catch语句块,执行完再执行finally语句块,最后结束。 2,try-finally,

如果在try语句块中执行到return语句前一条,未遇到异常,转而执行finally语句块,执行完再执行try中的return语句。 不要用return、break、continue或throw来退出finally语句块

正确用法 //该方法返回false

static boolean f() { try { return true; } finally { //不做return操作 } }

评论(3)

  1. #3 楼 · 无愧衾影 · 2011-03-24 13:53

    正确,return 要放在正确的地方

  2. #2 楼 · jkxydp · 2011-03-03 20:07

    不好意思,楼主,我这样写也不对,这样程序会把抛出的异常活生生地吃掉,而且我还发现了一个新的问题 public class Test { public static void main(String args) { try { System.out.println(k()); } catch (RuntimeException e) { System.out.println("main:runtime" ); } } public static int k() throws RuntimeException{ int x = 0; try{ System.out.println("try"); throw new RuntimeException("runtime"); } catch (RuntimeException e) { System.out.println("catch"); x = 1; throw e; } finally { System.out.println("finally"); }

    }
    

    } 你看那个k方法,居然没写return语句也能正常执行,编译运行都不报错! 非常迷惑,希望有人能够解释它!

  3. #1 楼 · jkxydp · 2011-03-03 18:38

    return语句并非不能在finally里面写,得看怎么写,比如 public int add() { int flag = 0; try{ xxxDao.save(XXX); flag = 1; }catch(RuntimeException e) { flag = 2; threw e; }finally { return flag; }

评论功能维护中,当前仅展示历史评论。