- package Test;
- public class TestException {
- public TestException() {
- }
- boolean testEx() throws Exception {
- boolean ret = true;
- try {
- ret = testEx1();
- } catch (Exception e) {
- System.out.println("testEx, catch exception");
- ret = false;
- throw e;
- } finally {
- System.out.println("testEx, finally; return value=" + ret);
- return ret;
- }
- }
- boolean testEx1() throws Exception {
- boolean ret = true;
- try {
- ret = testEx2();
- if (!ret) {
- return false;
- }
- System.out.println("testEx1, at the end of try");
- return ret;
- } catch (Exception e) {
- System.out.println("testEx1, catch exception");
- ret = false;
- throw e;
- } finally {
- System.out.println("testEx1, finally; return value=" + ret);
- return ret;
- }
- }
- boolean testEx2() throws Exception {
- boolean ret = true;
- try {
- int b = 12;
- int c;
- for (int i = 2; i >= -2; i--) {
- c = b / i;
- System.out.println("i=" + i);
- }
- return true;
- } catch (Exception e) {
- System.out.println("testEx2, catch exception");
- ret = false;
- throw e;
- } finally {
- System.out.println("testEx2, finally; return value=" + ret);
- return ret;
- }
- }
- public static void main(String[] args) {
- TestException testException1 = new TestException();
- try {
- testException1.testEx();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- 答案:
-
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
-
- 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";
- }
- }
finally块中的return语句会覆盖try块中的return返回。
这说明finally里的return直接返回了,就不管try中是否还有返回语句,这里还有个小细节需要注意,finally里加上return过后,finally外面的return b就变成不可到达语句了,也就是永远不能被执行到,所以需要注释掉否则编译器报错。