java 中 finally里面写了return 会发生什么?
boolean test() throws Exception { boolean ret = true; try { int b = 12; int c; for (int i = 1; i >= -2; i--) { c = b / i; System.out.println("i=" + i); } return true; } catch (Exception e) { System.out.println("testEx2, catch exception"); ret = false; throw e; } finally { System.out.println("testEx2, finally; return value=" + ret);
return ret; } }
这是一种很不好的写法。
开始认为会输出
i=12
testEx2, catch exception
testEx2, finally; return value=false
但事实是
i =12
testEx2, finally; return value=false
原因是finally里写return return会冲掉上边的return 并且干掉catch抛出的异常