Java try()语句实现 try-with-resources 异常管理机制

本文详细介绍Java7中新增的try-with-resources语句,该特性允许自动关闭资源,避免了在finally块中手动关闭资源的繁琐操作。文章通过示例对比了传统方式与新特性在资源管理上的差异,并展示了如何自定义实现AutoCloseable接口以利用这一特性。

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

java7 新增特性,对于try语句块中使用到的资源,不再需要手动关闭,在语句块结束后,会自动关闭,类似于python的with..as的用法。

利用这个特性,需要实现AutoCloseable接口,只有一个close方法,实现关闭资源的操作。

public interface AutoCloseable{
    public void close() throws Exception;
}

所有的流,都实现了这个接口,可以在try()中进行实例化。自定义的类只要实现了这个接口,也可以使用这个特性。

不使用try-with-resources时,使用的资源要在finally中进行释放。

package stream;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class TestStream {
 
    public static void main(String[] args) {
        File f = new File("d:/test.txt");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f); 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 在finally 里关闭流
            if (null != fis)
                try { 
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
 
    }
}

 使用try-with-resources时

形式为try(),括号内可以包含多个语句。

package stream;
  
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
  
public class TestStream {
  
    public static void main(String[] args) {
        File f = new File("d:/lol.txt");
  
        //把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
        try (FileInputStream fis = new FileInputStream(f)) {
            byte[] all = new byte[(int) f.length()];
            fis.read(all);
            for (byte b : all) {
                System.out.println(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
  
    }
}

自定义AutoCloseable实现

在TestAutoCloseable的close方法中打印信息

package test;

public class TestAutoCloseable implements AutoCloseable{
	public TestAutoCloseable() {
		System.out.println("class TestAutoCloceable");
	}
	public void close() {
		System.out.println("function close() executed");
	}
}

测试代码

package test;

public class TestFeature {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try(TestAutoCloseable testAutoCloseable = new TestAutoCloseable()){
			
		}
	}

}

结果close方法被调用

参考 

Java7 新特性:try() 语句 即 try-with-resources

I/O 关闭流的方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值