, ( , close)
, , , .
,
, , .
:
, A, B and C,
1 (s) 2 Throwable getSuppressed.
, -, , , close () . , - .
try..catch. - , , , - . - close , ( getSuppressed ).
, - , , -.
Resources - , .
public class Resources implements AutoCloseable {
private MyCloseable1 myCloseable1;
private MyCloseable2 myCloseable2;
public Resources() {
try {
myCloseable1 = new MyCloseable1();
myCloseable2 = new MyCloseable2();
} catch (Exception e) {
close(false, myCloseable1, myCloseable2);
throw new RuntimeException("Initialization failed");
}
}
@Override
public void close() throws Exception {
close(true, myCloseable1, myCloseable2);
}
private void close(boolean throwExceptionIfFailed, AutoCloseable... autoCloseables) {
boolean closeFailed = false;
for (AutoCloseable autoCloseable : autoCloseables) {
try {
if (autoCloseable != null) {
autoCloseable.close();
}
} catch (Exception e) {
closeFailed = true;
}
}
if (closeFailed && throwExceptionIfFailed) {
throw new RuntimeException("Closing of Resources failed");
}
}
}
:
try (Resources resources = new Resources()) {
....
} catch (Exception e) {
....
}