/**
* Closes all given <tt>Closeable</tt>s. Some of the
* <tt>Closeable</tt>s may be null; they are
* ignored. After everything is closed, the method either
* throws the first exception it hit while closing, or
* completes normally if there were no exceptions.
*
* @param objects
* objects to call <tt>close()</tt> on
*/
public static void close(Closeable... objects) throws IOException {
close(Arrays.asList(objects));
}
/**
* Closes all given <tt>Closeable</tt>s.
* @see #close(Closeable...)
*/
public static void close(Iterable<? extends Closeable> objects) throws IOException {
Throwable th = null;
for (Closeable object : objects) {
try {
if (object != null) {
object.close();
}
} catch (Throwable t) {
addSuppressed(th, t);
if (th == null) {
th = t;
}
}
}
reThrow(th);
}
/**
* Closes all given <tt>Closeable</tt>s, suppressing all thrown exceptions.
* Some of the <tt>Closeable</tt>s may be null, they are ignored.
*
* @param objects
* objects to call <tt>close()</tt> on
*/
public static void closeWhileHandlingException(Closeable... objects) {
closeWhileHandlingException(Arrays.asList(objects));
}
/**
* Closes all given <tt>Closeable</tt>s, suppressing all thrown exceptions.
* @see #closeWhileHandlingException(Closeable...)
*/
public static void closeWhileHandlingException(Iterable<? extends Closeable> objects) {
for (Closeable object : objects) {
try {
if (object != null) {
object.close();
}
} catch (Throwable t) {
}
}
}
/** adds a Throwable to the list of suppressed Exceptions of the first Throwable
* @param exception this exception should get the suppressed one added
* @param suppressed the suppressed exception
*/
private static void addSuppressed(Throwable exception, Throwable suppressed) {
if (exception != null && suppressed != null) {
exception.addSuppressed(suppressed);
}
}