我正在尝试使用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()
方法?