7-3异常处理----异常处理机制一: try-catch-finally(2)finally的使用

这篇博客探讨了Java中finally块的重要性和使用场景。finally块确保代码中定义的清理操作总会执行,无论是否发生异常,比如关闭数据库连接、输入输出流。示例代码展示了在try-catch-finally结构中如何正确处理文件读取和关闭,以及finally块如何在存在return语句和额外异常时仍然执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

finally的使用

1.finally是可选的。
2.finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。
3.像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
代码:

package test1;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import org.junit.Test;
 
public class FinallyTest {
 
 @Test
 public void test2() {
  FileInputStream fis = null;
  try {
   File file = new File("hello.txt");
   fis = new FileInputStream(file);
 
   int data = fis.read();
   while (data != -1) {
    System.out.print((char) data);
    data = fis.read();
   }
 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fis != null)
     fis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 
 @Test
 public void testMethod() {
  int num = method();
  System.out.println(num);
 }
 
 public int method() {
 
  try {
   int[] arr = new int[10];
   System.out.println(arr[10]);// 出异常,跳过return 1;
   return 1;
  } catch (ArrayIndexOutOfBoundsException e) {
   e.printStackTrace();
   return 2;
  } finally {
   System.out.println("一定会执行");
//   return 4;
  }
 
 }
 
 @Test
 public void test1() {
  try {
   int a = 10;
   int b = 0;
   System.out.println(a / b);
 
  } catch (ArithmeticException e) {
   e.printStackTrace();
 
   // 又出现一个异常
//   int[] arr = new int[10];
//   System.out.println(arr[10]);
 
  } catch (Exception e) {
   e.printStackTrace();
  }
//  System.out.println("结束2021.1.31!!!");
 
  finally {// 一定会执行
   System.out.println("结束2021.1.31");
  }
 
 }
}

输出(略)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YY鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值