private void test(){
try{
TestException te = this.new TestException();
te.test();
System.out.println("trytrytry");
} catch (Exception e){
e.printStackTrace();
System.out.println("catchcatchcatch");
} finally {
System.out.println("finallyfinallyfinally");
}
System.out.println("endendend");
}
private class TestException {
void test() throws Exception{
throw new Exception("illegal invoked");
}
}
这个程序返回的结果为:
java.lang.Exception: illegal invoked at com.alu.gesdp.integration.ldap.LDAPIntegration$TestException.test(LDAPIntegration.java:839) at com.alu.gesdp.integration.ldap.LDAPIntegration.test(LDAPIntegration.java:826) at com.alu.gesdp.integration.ldap.LDAPIntegration.main(LDAPIntegration.java:820) catchcatchcatch finallyfinallyfinally endendend
为了理解 finally 与 finally 后的代码之间的关系,写了这个程序。
结论是,写在finally内,与写在finally后基本是相同的。写在finally内代码更美观,更易于维护。
try – catch 的目的就是代码可以在抛出异常后继续运行,所以基本不存在抛出异常后,随后的代码不可执行的情况。也就是说,其实写在finally 之内或之后是一样的。
还有 try+finally 的情况,ZT
http://blog.csdn.net/lovecj6185/article/details/4461516
try+finally
程序的流程是:运行到try块中,如果有异常抛出的话,程序转向执行finally块的代码。那末finally块后面的代码还会被执行吗?不会!因为你没有处理异常,所以遇到异常后,执行完finally后,方法就已抛出异常的方式退出了。
这种方式中要注意的是,由于你没有捕获异常,所以要在方法后面声明抛出异
