有程序1需要对文件进行读取操,另一个程序2对想对文件进行删除操作;请问程序2能否成功?
回答:不能。---资源文件一旦使用完毕,一定要释放资源文件,否则其他的程序无法对这个资源文件进行操作。
引出:finally 块
finally 块的使用前提是必须要存在try块才能使用。
finally 块的代码在任何情况下都会执行的,除了jvm退出的情况。
finally 非常适合做资源释放的工作,这样子可以保证资源文件在任何情况下都会被释放。
第一种情况:
public class Exception_05 { public static void main(String[] args) { // TODO Auto-generated method stub div(4,0); } public static void div(int a, int b){ //第一种情况 try{ int c = a/b; System.out.println("c="+ c); }catch(Exception e){ System.out.println("出了除数为0的异常..."); throw e; }finally{ System.out.println("finall块的代码执行了.."); } } }
运行结果:
Exception in thread "main" 出了除数为0的异常... finall块的代码执行了.. java.lang.ArithmeticException: / by zero at test_01.Exception_05.div(Exception_05.java:34) at test_01.Exception_05.main(Exception_05.java:13)
第二种情况:
public class Exception_05 { public static void main(String[] args) { // TODO Auto-generated method stub div(4,0); } //第二种情况 public static void div(int a, int b){ try{ if(b==0){ return; } int c = a/b; System.out.println("c="+ c); }catch(Exception e){ System.out.println("出了除数为0的异常..."); throw e; }finally{ System.out.println("finall块的代码执行了.."); } } }
运行结果:
finall块的代码执行了..
第三种情况:
public class Exception_05 { public static void main(String[] args) { // TODO Auto-generated method stub div(4,0); } //第三种情况 public static void div(int a, int b){ try{ if(b==0){ System.exit(0);//退出jvm } int c = a/b; System.out.println("c="+ c); }catch(Exception e){ System.out.println("出了除数为0的异常..."); throw e; }finally{ System.out.println("finall块的代码执行了.."); } } }
try块的三种组合方式:
第一种: 比较适用于有异常要处理,但是没有资源要释放的。 try{ 可能发生异常的代码 }catch(捕获的异常类型 变量名){ 处理异常的代码 } 第二种:比较适用于既有异常要处理又要释放资源的代码。 try{ 可能发生异常的代码 }catch(捕获的异常类型 变量名){ 处理异常的代码 }finally{ 释放资源的代码; } 第三种: 比较适用于内部抛出的是运行时异常,并且有资源要被释放。 try{ 可能发生异常的代码 }finally{ 释放资源的代码; }
释放资源的代码:
public class finally_01 { public static void main(String[] args) { // TODO Auto-generated method stub FileReader fileReader = null; try{ //找到目标文件 File file = new File("E:\\a.txt"); //建立程序与文件的数据通道 fileReader = new FileReader(file); //读取文件 char[] buf = new char[1024]; //使用字符数组来读取文件 int length = 0; length = fileReader.read(buf); //读的过程 System.out.println("读取到的内容:"+ new String(buf,0,length)); }catch(IOException e){ System.out.println("读取资源文件失败...."); }finally{ try{ //关闭资源 fileReader.close(); System.out.println("释放资源文件成功...."); }catch(IOException e){ System.out.println("释放资源文件失败...."); } } } }