java异常处理05_try_with_resource

众所周知,所有被打开的系统资源,比如流、文件、Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。

在JDK1.7以前,我们想要关闭资源就必须的finally代码块中完成。

【示例】JDK7之前资源的关闭的方式

/**
 * 测试类
 */
public class Test {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = null;
        try {
        	// 创建字节输入流,注意:“file.txt”文件在项目中不存在,则会抛出异常
            inputStream = new FileInputStream("file.txt");
            // 执行存储数据的操作,此处省略。。。
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
            	// 关闭流
                inputStream.close();
            }
        }
    }
}

JDK7及以后关闭资源的正确姿势:try-with-resource,该语法格式:

try(/*需要关闭的资源*/){
	// 容易出现异常的代码
}catch(Exception e) {
	// 处理异常
}

Resource的定义:所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

【示例】实现对try-with-resource的验证

/**
 * 资源类
 */
class Resource implements AutoCloseable {
    public void sayHello() {
        System.out.println("hello");
    }
    @Override
    public void close() throws Exception {
        System.out.println("Resource is closed");
    }
}
/**
 * 测试类
 */
public class Test{
	public static void main(String[] args) {
		try(Resource resource = new Resource()) {
            resource.sayHello();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

输出结果为:
在这里插入图片描述

【示例】当存在多个打开资源的时候

/**
 * 资源类
 */
class Resource1 implements AutoCloseable {
    public void sayHello() {
        System.out.println("Resource1 hello");
    }
    @Override
    public void close() throws Exception {
        System.out.println("Resource is closed");
    }
}
class Resource2 implements AutoCloseable {
    public void sayHello() {
        System.out.println("Resource2 hello");
    }
    @Override
    public void close() throws Exception {
        System.out.println("Resource is closed");
    }
}
/**
 * 测试类
 */
public class Test{
	public static void main(String[] args) {
		try(Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {
            r1.sayHello();
            r2.sayHello();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

输出结果为:
在这里插入图片描述
通过try-with-resource来释放资源,即使资源很多,代码也可以写的很简洁,如果用JDK1.7之前的方式去关闭资源,那么资源越多,用fianlly关闭资源时嵌套也就越多。

ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值