finally块:
finally块的使用前提是必须要存在try块才能使用。
finally块的代码在任何情况下都会执行,除了jvm退出的情况。
finally块非常适合做资源释放的工作。
/*** Author:Liu Zhiyong* Version:Version_1* Date:2016年6月22日22:04:32* Desc:finally块 finally块的使用前提是必须要存在try-catch块才能使用。 finally块的代码在任何情况下都会执行,除了jvm退出的情况。 finally块非常适合做资源释放的工作。*/class Demo69 { public static void main(String[] args) { div(4, 0); } public static void div(int a, int b){ try { System.out.println("出现异常前。。。。"); if(b == 0){ // return;//(函数一旦执行到了return关键字,那么该函数马上结束。)finally块里面的还是能执行 System.exit(0); //退出jvm } int c = a / b; System.out.println("c="+c); } catch (Exception e) { System.out.println("除数不能为0。。。。"); throw e; //throw也能结束异常(一个方法遇到了throw关键字的话,方法会马上停止执行) }finally{ System.out.println("finally块执行了。。。。"); } }}
finally块释放资源demo:
/*** Author:Liu Zhiyong* Version:Version_1* Date:2016年6月23日23:11:15* Desc:finally块释放资源的代码 */import java.io.*;class Demo70 { public static void main(String[] args) { FileReader fileReader = null; try { //找到目标文件 File file = new File("f:/a.txt"); //建立程序 fileReader = new FileReader(file); //读取文件 char[] buff = new char[1024]; int length = 0;; length = fileReader.read(buff); System.out.println("读取到的内容如下:\n-----------------\n" + new String(buff, 0, length) + "\n-----------------"); } catch (IOException e) { System.out.println("读取资源文件失败。。。"); e.printStackTrace(); }finally{ try { //关闭资源 fileReader.close(); System.out.println("释放资源成功。。。"); }catch (IOException e) { System.out.println("释放资源失败。。。"); } } }}