阅读时间: 10分钟
在学习Java时,相信都会看过finally这个关键字。
而它与final同样也是属于Java中的保留字,所以不能用作识别字(identifier)。
finally的作用是配合try/catch block使用,以保证在finally的block内的代码会被执行,
即使遇到exception的情况。
我会用例子加以说明:
有Exception,但没有处理
class Martin{ public static void main(String args[]) { //Method A static void A() { try { System.out.println("显示A"); throw new Exception(); //没有处理Exception } finally { System.out.println("A finally"); } } }
有Exception,会被处理
class Martin{ public static void main(String args[]) { //Method B static void B() { try { System.out.println("显示B"); throw new Exception(); } catch (Exception e) { System.out.println("Exception caught"); } finally { System.out.println("B finally"); } } }
在try block内出现return
class Martin{ public static void main(String args[]) { // Method C static void C() { try { System.out.println("显示C"); return; //直接return,结束这个method } finally { System.out.println("C finally"); } } }
在catch block内出现return
class Martin{ public static void main(String args[]) { //Method D static void D() { try { System.out.println("显示D"); } catch (Exception e){ System.out.println("D catch"); return; } finally { System.out.println("D finally"); } } }
从例子可以看到不管在什么情况,在finally内的block的代码都会被执行。
只有在整个操作系统停止时,才会不被执行。