- 在异常捕获中,有时会有需要显示地回收一些物理资源(java垃圾回收机制是不会回收物理资源的,它只会回收堆内存中对象占用的内存)
- 如果在try中回收资源的话,那么处在抛出异常之后的代码将没有机会执行,这样一来回收资源的语句就不会被执行了,如果在catch中回收的话,可能因为catch代码块没有执行导致资源没有回收,这个时候就有了finally代码块存在的意义,只要没有执行退出虚拟机的操作,finally代码块中的逻辑都会执行。
- 需要指出的是,try是一场捕获中不能缺少的,catch和finally至少出现一个
- 代码示例
package KnowIt; import java.io.FileInputStream; import java.io.IOException; public class FinallyTest { public static void main(String args[]){ FileInputStream fis = null; try{ fis = new FileInputStream("a.txt"); }catch (IOException ioe){ System.out.println(ioe.getMessage()); return; }finally { if(fis != null){ try{ fis.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } System.out.println("执行finally语句"); } } } //输出结果: // a.txt (The system cannot find the file specified) // 执行finally语句
-
需要指出的是,在finally中,不要放返回语句,否则会使得try和catch中的代码失效,因为finally是最后执行的,会覆盖前面的结果,一下的代码示例
package KnowIt; public class FinallyFlow { public static void main(String args[]) throws Exception{ boolean a = test(); System.out.println(a); } public static boolean test(){ try{ return true; }finally { return false; } } } //输出结果为 // false
java异常捕获(3)finally代码块
猜你喜欢
转载自blog.csdn.net/weixin_39452731/article/details/81748642
今日推荐
周排行