public class TestException {
public static void main(String[] args) {
System.out.print(tt());
}
public static int tt() {
int b = 23;
try {
System.out.println("yes");
return b += 88;
} catch (Exception e) {
System.out.println("error : " + e);
} finally {
if (b > 25) {
System.out.println("b>25 : " + b);
}
System.out.println("finally");
}
return b;
}
}
运行结果:
yes
b>25 : 111
finally
111
也就是说明finally语句在return语句执行完了以后才执行的.
OK,那么问题来了,如果我把finally语句改成这样呢:
public class TestException {
public static void main(String[] args) {
System.out.print(tt());
}
@SuppressWarnings("finally")
public static int tt() {
int b = 23;
try {
System.out.println("yes");
return b += 88;
} catch (Exception e) {
System.out.println("error : " + e);
} finally {
if (b > 25) {
System.out.println("b>25 : " + b);
}
System.out.println("finally");
return 100;
}
}
}
yes
b>25 : 111
finally
100
这样又说明了一个问题,finally语句块里面的return把原来的return给覆盖了!!变成了新的返回值了.
倘若改成这样:
public class TestException {
public static void main(String[] args) {
System.out.print(tt());
}
@SuppressWarnings("finally")
public static int tt() {
int b = 23;
try {
System.out.println("yes");
return b;
} catch (Exception e) {
System.out.println("error : " + e);
} finally {
if (b > 25) {
System.out.println("b>25 : " + b);
}
System.out.println("finally");
b= 100;
}
return b;
}
}
打印结果:
yes
finally
23
说明了一个问题,如果finally语句中没有返回语句覆盖的话,那么原来的返回值就不会变,不管你是不是改变了要返回的那个变量.
最后总结:
碰到try语句中的return,那么先把return的值放在某个池中(怎么我也说起池来了,明明根本还不懂的)?
然后执行finally里面的代码块,如果有返回值覆盖语句,就改变先前放在池中的那个值, 如果没有, 就把那个池中的东西取出来返回出去.
public class FourTest{
/**
* @param args
*/
public static int getInt (String message) {
int x = 0;
try{
return x = Integer.parseInt(message);
}catch(NumberFormatException e){
}finally{
x = 100;
}
return x;
}
public static void main(String[] args){
System.out.println(FourTest.getInt("1001"));
// 若是 1001 则打印 1001
// 若是 1001s 则打印 100
}
}