释放资源的方式

本文详细解释了Java中try-catch-finally语句的作用,尤其是在处理异常和资源管理方面的应用,以及JDK7引入的try-with-resources简化了资源关闭过程。

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

try - catch - finally

  • finally代码区的特点:无论try中的程序是正常执行力,还是出现了异常,最后都一定会执行finally区,除非JVM终止。 
  • 作用:一般用于在程序执行完成后进行资源的释放操作(专业级做法)。
public class Test {
    public static void main(String[] args) throws Exception {
        try {
            System.out.println(10 / 2);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("===finally执行了一次===");
        }

        System.out.println(chu(10,2));
    }

    private static int chu(int a, int b) {
        try {
            return a / b;
        }catch (Exception e){
            e.printStackTrace();
            return -1; // 代表的是出现异常
        }finally {
            // 千万不要在finally中返回数据
            return 111;
        }
    }
}
import java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        InputStream is = null;
        OutputStream os = null;
        try {
            System.out.println(10 / 0);
            is = new FileInputStream("D:/tp/123/666.jpg");
            os = new FileOutputStream("C:/abc/qwer/666.jpg");

            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read()) != -1){
                os.write(bytes,0,len);
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源的操作
            try {
                if (os != null) os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

JDK7开始提供了更简单的资源释放方案:try - with - resource

该资源使用完毕后,会调用其close()方法,完成对资源的释放 

  •  ()中只能放资源,否则报错
  • 资源一般指的是最终实现了AutoCloseable接口
import java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        try(
                InputStream is = new FileInputStream("D:/tp/123/666.jpg");
                OutputStream os = new FileOutputStream("C:/abc/qwer/666.jpg");

                // 注意:这里只能放置资源对象(流对象)
                // 资源都是会实现AutoCloseable接口,资源都会有一个close方法
                // 用完之后,会自动调用其close方法完成资源的释放操作
            ) {

            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read()) != -1){
                os.write(bytes,0,len);
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值