老年人随手记/第二卷/漂亮的代码-哪些写断手的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处理代码。

发布了11 篇原创文章 · 获赞 6 · 访问量 9568

猜你喜欢

转载自blog.csdn.net/u014174048/article/details/87170963