第一种情况:try中有return语句,而finally中没有- public class TestTry
- {
- static String s="";
- public static void main(String args[])
- {
- s = test1();
- System.out.println("8 "+s);
- }
- public static String test1()
- {
-
- try
- {
- System.out.println("try.....");
- return s = "a";
- }
- finally{
- s="b";
- System.out.println("17 "+s);
- }
- }
- }
- 运行结果为:try.....
- 17 b
- 8 a
复制代码
第二种情况:try中没有return语句,finally中有return语句- public class TestTry
- {
- static String s="";
- public static void main(String args[])
- {
- s = test1();
- System.out.println("8 "+s);
- }
- public static String test1()
- {
-
- try
- {
-
- System.out.println("try.....");
- }
- finally
- {
- s="b";
- System.out.println("17 "+s);
- }
- }
- }
- 运行结果为:try.....
- 17
- 8 b
复制代码
第三种情况:try和finally中都有return语句- public class TestTry
- {
- static String s="";
- public static void main(String args[])
- {
- s = test1();
- System.out.println("8 "+s);
- }
- public static String test1()
- {
-
- try
- {
- System.out.println("try.....");
- return s = "a";
- }
- finally
- {
- return s="b";
-
- }
- }
- }
- 运行结果为:try.....
- 8 b
复制代码
总结:无论try中有没有return语句,finally语句都一定要执行。当try中有return语句时,finally中没有return时,那么在执行try中return之前先执行finally语句。当finally有return语句时,无论try中有没有return,将会直接返回,不再去执行try中的return语句。 |
|