История изменений
Исправление
Weres,
(текущая версия)
:
Сильно позже. Это появилось в Java 7 (2011 год).
Завершается блок try - вызываются close для объявленных между скобок ресурсов. Если внутри блока выскочит исключение, то close будет вызван всё равно. Отвечу песней:
try (ExceptionCloseable closeable = new ExceptionCloseable()){
try (JustCloseable justCloseable = new JustCloseable()) {
throw new Exception("Inner exception");
}
}
catch (IOException e) {
System.out.print("IO: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Other:" + e.getMessage());
System.out.println("Suppress exception: " + e.getSuppressed()[0].getMessage());
}
private static class ExceptionCloseable implements Closeable {
@Override
public void close() throws IOException {
throw new IOException("Close exception");
}
}
private static class JustCloseable implements Closeable {
@Override
public void close() throws IOException {
System.out.println("Close JustCloseable");
}
}
Close JustCloseable
Other:Inner exception
Suppress exception: Close exception
Если что, я не против С++ и концепции деструкторов. Она мне нравится. Просто показал способ.
Исходная версия
Weres,
:
Сильно позже. Это появилось в Java 7 (2011 год).
Завершается блок try - вызываются close для объявленных между скобок ресурсов. Если внутри блока выскочит исключение, то close будет вызван всё равно. Отвечу песней:
try (ExceptionCloseable closeable = new ExceptionCloseable()){
try (JustCloseable justCloseable = new JustCloseable()) {
throw new Exception("Inner exception");
}
}
catch (IOException e) {
System.out.print("IO: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Other:" + e.getMessage());
System.out.println("Suppress exception: " + e.getSuppressed()[0].getMessage());
}
private static class ExceptionCloseable implements Closeable {
@Override
public void close() throws IOException {
throw new IOException("Close exception");
}
}
private static class JustCloseable implements Closeable {
@Override
public void close() throws IOException {
System.out.println("Close JustCloseable");
}
}
Close JustCloseable
Other:Inner exception
Suppress exception: Close exception
Если что, я не против С++ и концепции деструкторов. Она мне нравится. Просто показал способ.