老年人随手记/第二卷/漂亮的代码-哪些写断手的finally和遗忘的资源

在实际开发中,我们经常碰到资源的读写开关,例如我们在读取一个文件的时候,安装之前的代码习惯大部分是这样实现的:

(此处代码来自互联网)

public static void main(String[] args) throws Throwable {

        try {

            FileInputStream ins = new FileInputStream(new File("temp"));

            Throwable throwException = null;

            try {

                System.out.println(ins.read());

            } catch (Throwable throwable) {

                throwException = throwable;

                throw throwable;

            } finally {

                if (ins != null) {

                    if (throwException != null) {

                        try {

                            ins.close();

                        } catch (Throwable var11) {

                            throwException.addSuppressed(var11);

                        }

                    } else {

                        ins.close();

                    }

                }

            }

        } catch (IOException exception) {

            throw new RuntimeException(exception.getMessage(), exception);

        }

    }

 

其实自1.7之后,try-with-resource能比较优雅的处理资源的关闭问题。

改进后的代码如下:

 public static void main(String[] args) throws Throwable {

        try (FileInputStream ins = new FileInputStream(new File("temp"));) {

            Throwable throwException = null;

            try {

                System.out.println(ins.read());

            } catch (Throwable throwable) {

                throwException = throwable;

                throw throwable;

            }

        } catch (IOException exception) {

            throw new RuntimeException(exception.getMessage(), exception);

        }

    }

 

这样就省去了一大段finally处理代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值