黑马程序员技术交流社区

标题: try {}里有一个return语句,那么紧跟在这个try后的finally {}里... [打印本页]

作者: ln0491    时间: 2015-8-29 11:39
标题: try {}里有一个return语句,那么紧跟在这个try后的finally {}里...
  1. package com;

  2. public class Test1 {

  3.         public static void main(String[] args) {
  4.                
  5.                 System.out.println(new Test1().test());
  6.                
  7.         }
  8.         static int test()

  9.         {

  10.         int x = 1;

  11.         try

  12.         {

  13.         return x;

  14.         }

  15.         finally

  16.         {

  17.     System.out.println(++x);

  18.         }

  19.         }


  20. }
复制代码
结果:2,1
再如果finally中也有return 结果会什么样

  1. package com;

  2. public class Test1 {

  3.         public static void main(String[] args) {
  4.                
  5.                 System.out.println(new Test1().test());
  6.                
  7.         }
  8.         static int test()

  9.         {

  10.         int x = 1;

  11.         try

  12.         {

  13.         return x;

  14.         }

  15.         finally

  16.         {

  17.     return ++x;

  18.         }

  19.         }


  20. }
复制代码

结果是:2
看下面这个
  1. package com;

  2. public class Test1 {

  3.         public static void main(String[] args) {

  4.                 System.out.println(new Test1().test());

  5.         }

  6.         static int test()

  7.         {

  8.                 int x = 1;

  9.                 try

  10.                 {
  11.                         System.out.println("try return ");
  12.                         return x;

  13.                 }

  14.                 finally {
  15.                         System.out.println("finally return ");
  16.                         return ++x;

  17.                 }

  18.         }

  19. }
复制代码

结果:
try return
finally return
2







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2