Java教程

Java 7 新特性之try-with-resources实践理解

本文主要是介绍Java 7 新特性之try-with-resources实践理解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

想象这么一个情景,我们需要使用一个资源,在使用完之后需要关闭该资源,并且使用该资源的过程中有可能有异常抛出。此时我们都会想到用try-catch语句,在finally中关闭该资源。此时会有一个问题,如果关闭该资源的时候也抛出了异常呢?见如下例子:

package com.rundong;

import java.io.IOException;

public class ResourceTest implements AutoCloseable{
    @Override
    public void close() throws IOException {
        throw new IOException("close Exception");
    }
}
package com.rundong;

import java.io.IOException;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        try {
            throwTest();
        } catch (SQLException e) {
            System.out.println("catch SQLException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("catch IOException");
            e.printStackTrace();
        }
    }

    static void throwTest() throws SQLException, IOException {
        ResourceTest resource = null;
        try {
            resource = new ResourceTest();
            throw new SQLException("the first Exception");
        } catch (SQLException e) {
            System.out.println("catch the first Exception");
            // do something
            throw e;
        } finally {
            if (resource != null) resource.close();
        }
    }
}

输出结果:

 发现什么问题了吗?

finally中抛出的异常将try中抛出的异常覆盖了!我们无法捕获到第一个异常!

 

Java 7 的解决方式:

package com.rundong;

import java.io.IOException;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        try {
            throwTest();
        } catch (SQLException e) {
            System.out.println("catch SQLException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("catch IOException");
            e.printStackTrace();
        }
    }

    static void throwTest() throws SQLException, IOException {
        try (ResourceTest resource = new ResourceTest()) {
            throw new SQLException("the first Exception");
        } catch (SQLException e) {
            System.out.println("catch the first Exception");
            // do something
            throw e;
        }
    }
}

 

输出结果:

 try-with-resources的写法就能很好的处理这样的情景,它会自动关闭资源,并且如果关闭资源时也抛出了异常,不会覆盖原有异常的抛出。

使用条件:实现了AutoCloseable接口的类。

 

同时,这也提示着我们,永远不要尝试在finally中抛出异常!

这篇关于Java 7 新特性之try-with-resources实践理解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!