将代码写在finally块中与写在trycatch底下有区别,这个区别体现在catch没能够捕捉到异常,致使异常继续上抛的时候。
1 static void test1() throws Exception { 2 try { 3 throw new Exception("exception"); 4 }catch (RuntimeException e) { 5 e.printStackTrace(); 6 System.out.println("catch"); 7 }finally { 8 System.out.println("finally"); 9 } 10 System.out.print("end"); 11 }
执行结果:
虽然try块中的代码因为异常的出现没有执行完成,catch块中的代码因为没有捕获到异常而没有得到执行,但finally块中的代码仍然得到了执行。而最终第十行的end没有打印出来,因为trycatch块执行完时产生了异常,跳过了该语句