package com.zl.test;

// try catch finally 内有return
public class Demo {

public static void main(String args[]) {

Demo d = new Demo();

int num = 10;
System.out.println(d.test(num));// 11
System.out.println("---------------------------");
System.out.println(d.testReturn(num));// 12
System.out.println("---------------------------");
System.out.println(num);// 10
}

public int test(int b) {
try {
System.out.println("1------------");
b += 1;
return b;
} catch (RuntimeException e) {
} catch (Exception e2) {
} finally {
b += 1;
System.out.println("2------------");
}
return 0;
}

// 11
// finally语句块执行完毕后,程序直接将之前缓冲的值返回了。

public int testReturn(int i) {

try {
System.out.println("1============");
++i;
return i;
} catch (Exception e) {
// ++i;
return i;
} finally {
++i;
System.out.println("2============");
System.out.println(i);
return 1;
}
}
// 12
// 只有当finally语句中有return时finally语句内对catch中return的值得修改才生效;
}

/* Output:

1------------
2------------
11
---------------------------
1============
2============
12
1
---------------------------
10

*/

05-11 15:24
查看更多