try、finally、return 悠悠 2022-04-18 06:14 221阅读 0赞 **finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句不能影响try或catch中 return已经确定的返回值,若finally里也有return语句则覆盖try或catch中的return语句直接返回。** **在try块中有System.exit(0);这样的语句,System.exit(0);是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。** **例子:** public class FinallyTest1 { public static void main(String[] args) { System.out.println(test1()); } public static int test1() { int b = 20; try { System.out.println("try block"); return b += 80; } catch (Exception e) { System.out.println("catch block"); } finally { System.out.println("finally block"); if (b > 25) { System.out.println("b>25, b = " + b); } } return b; } } 运行结果是: try block finally block b>25, b = 100 100 **下面这种情况下return的值会被覆盖的,因为Java里只有传值,传对象也只是传对象的地址,而且是值传递:** public static void main(String[] args) { System.out.println(getMap().get("KEY").toString()); } public static Map<String, String> getMap() { Map<String, String> map = new HashMap<String, String>(); map.put("KEY", "INIT"); try { map.put("KEY", "TRY"); return map; } catch (Exception e) { map.put("KEY", "CATCH"); } finally { map.put("KEY", "FINALLY"); } return map; } <table> <tbody> <tr> <td> </td> <td> </td> </tr> </tbody> </table>
还没有评论,来说两句吧...