- try中有return:先执行try代码块,return语句或者函数也先执行,然后执行finally语句,最后执行try中的return返回结果。
public class FinallyTest1 {
public static void main(String[] args) {
System.out.println(test11());
}
public static String test11() {
try {
System.out.println("try block");
return test12();
} finally {
System.out.println("finally block");
}
}
public static String test12() {
System.out.println("return statement");
return "after return";
}
}
结果:
try block
return statement
finally block
after return
- try中和finally中都有return,finally中return会覆盖try中return
public class FinallyTest2 {
public static void main(String[] args) {
System.out.println(test2());
}
public static int test2() {
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 200;
}
}
}
结果:
try block
finally block
b>25, b = 100
200
- 如果finally中没有return语句,只是修改返回值的语句,那么结果可能被修改也可能不会。如果try中return简单的值类型,finally中修改无效,如果try中return一个对象,finally中可以操作该对象。
public class FinallyTest3 {
public static void main(String[] args) {
System.out.println(test3());
}
public static int test3() {
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);
}
b = 150;
}
return 2000;
}
}
结果:
try block
finally block
b>25, b = 100
100
public class FinallyTest6
{
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");
map = null;
}
return map;
}
}
结果:
FINALLY
- try中发送异常的时候,try中的return语句不会执行,但是return行为会最后执行,catch和finally会执行并且会改变结果,因为被异常捕获,try-catch-finnaly块外面的return永远不会被执行。
public class FinallyTest4 {
public static void main(String[] args) {
System.out.println(test4());
}
public static int test4() {
int b = 20;
try {
System.out.println("try block");
b = b / 0;
return b += 80;
} catch (Exception e) {
b += 15;
System.out.println("catch block");
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
b += 50;
}
return 204;
}
}
结果:
try block
catch block
finally block
b>25, b = 35
85
- catch中如果有return,情况跟try中的return一致
public class FinallyTest5 {
public static void main(String[] args) {
System.out.println(test5());
}
public static int test5() {
int b = 20;
try {
System.out.println("try block");
b = b /0;
return b += 80;
} catch (Exception e) {
System.out.println("catch block");
return b += 15;
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
b += 50;
}
}
}
结果:
try block
catch block
finally block
b>25, b = 35
35
网友评论