什么时候应该在代码中使用Throwable.getSuppressed()和addSuppressed()?

时间:2019-09-28 20:43:46

标签: java try-with-resources try-finally

我正在尝试使用try-with-resources来理解我的方法。 这是我的示例方法。

public void a(File f) throws FileNotFoundException, IOException {
    try (FileInputStream fis = new FileInputStream(f)) { // suppose FileNotFoundException occurs here
        byte[] buffer = new byte[7];
        fis.read(buffer); // suppose IOException occurs here
    }
}

现在假设新FileInputStream()的FileNotFoundException和fis.read()的IOException发生了异常。

这是我的方法在另一个类中的使用。

try {
            a(new File(""));
        } catch (IOException ex) {
            ex.printStackTrace();

            Throwable[] suppressedExceptions = ex.getSuppressed();
            if (suppressedExceptions.length > 0)
                for (Throwable exception : suppressedExceptions)
                    System.err.println(exception.toString());
        }

与前面的代码相同。使用try-with-resources时是否应该始终使用getSuppressed()方法? 以及何时,何地以及如何使用addSuppressed()方法?

0 个答案:

没有答案