finally块

来源:互联网 发布:inxedu 完整源码 编辑:程序博客网 时间:2024/05/17 03:55
finally块:
finally块的使用前提是必须要存在try块才能使用。
finally块的代码在任何情况下都会执行,除了jvm退出的情况。
finally块非常适合做资源释放的工作。
  1. /**
  2. * Author:Liu Zhiyong
  3. * Version:Version_1
  4. * Date:2016年6月22日22:04:32
  5. * Desc:finally块
  6. finally块的使用前提是必须要存在try-catch块才能使用。
  7. finally块的代码在任何情况下都会执行,除了jvm退出的情况。
  8. finally块非常适合做资源释放的工作。
  9. */
  10. class Demo69
  11. {
  12. public static void main(String[] args)
  13. {
  14. div(4, 0);
  15. }
  16. public static void div(int a, int b){
  17. try
  18. {
  19. System.out.println("出现异常前。。。。");
  20. if(b == 0){
  21. //return;//(函数一旦执行到了return关键字,那么该函数马上结束。)finally块里面的还是能执行
  22. System.exit(0);//退出jvm
  23. }
  24. int c = a / b;
  25. System.out.println("c="+c);
  26. }
  27. catch (Exception e)
  28. {
  29. System.out.println("除数不能为0。。。。");
  30. throw e; //throw也能结束异常(一个方法遇到了throw关键字的话,方法会马上停止执行)
  31. }finally{
  32. System.out.println("finally块执行了。。。。");
  33. }
  34. }
  35. }
finally块释放资源demo:
  1. /**
  2. * Author:Liu Zhiyong
  3. * Version:Version_1
  4. * Date:2016年6月23日23:11:15
  5. * Desc:finally块释放资源的代码
  6. */
  7. import java.io.*;
  8. class Demo70
  9. {
  10. public static void main(String[] args)
  11. {
  12. FileReader fileReader = null;
  13. try
  14. {
  15. //找到目标文件
  16. File file = new File("f:/a.txt");
  17. //建立程序
  18. fileReader = new FileReader(file);
  19. //读取文件
  20. char[] buff = new char[1024];
  21. int length = 0;;
  22. length = fileReader.read(buff);
  23. System.out.println("读取到的内容如下:\n-----------------\n"
  24. + new String(buff, 0, length) + "\n-----------------");
  25. }
  26. catch (IOException e)
  27. {
  28. System.out.println("读取资源文件失败。。。");
  29. e.printStackTrace();
  30. }finally{
  31. try
  32. {
  33. //关闭资源
  34. fileReader.close();
  35. System.out.println("释放资源成功。。。");
  36. }catch (IOException e)
  37. {
  38. System.out.println("释放资源失败。。。");
  39. }
  40. }
  41. }
  42. }
0 0
原创粉丝点击