/**
* 1、不管try块、catch块中是否有return语句,finally块都会执行。
* 2、finally块中的return语句会覆盖前面的return语句(try块、catch块中的return语句),
* 所以如果finally块中有return语句,
* Eclipse编译器会报警告“finally block does not complete normally”。
* 3、如果finally块中包含了return语句,即使前面的catch块重新抛出了异常,则调用该方法的语句也不会获得catch块重新抛出的异常,
* 而是会得到finally块的返回值,并且不会捕获异常。
* @author Administrator
*
*/
public class TestEx {
public TestEx() {
}
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) {
TestEx testException1 = new TestEx();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}