class implements AutoCloseableがtry with resourceできる
BufferedReadearなど。
try blockの最後でclose()が呼ばれる
class implements AutoCloseableがnullの場合はNullpointerは発生しない。closeもしない
記述した順番と逆順でclose
class Sample implements Closeable {
String msg;
Sample(String msg) {
this.msg = msg;
}
@Override
public void close() {
System.out.println(this.msg + " close");
}
void method() {
System.out.println(this.msg + " method");
}
}
public class Outer {
public static void main(String args[]) {
Sample s = new Sample("s");
Sample s1 = new Sample("s1");
Sample s3 = new Sample("s3");
Sample s2 = null;
try (s;s1;s2;s3) {
method(s);
method(s2);
}
}
static void method(Sample s) {
if(s!=null) s.method();
}
}
s method
s3 close
s1 close
s close
try block, closeでexception occurの場合、
try block sideのexceptionが表面的なexception
close sideのexceptionは getSuppressed()で取得
class Sample implements Closeable {
String msg;
Sample(String msg) {
this.msg = msg;
}
@Override
public void close() {
System.out.println(this.msg + " close");
throw new RuntimeException();
}
void method() {
System.out.println(this.msg + " method");
}
}
public class Outer {
public static void main(String args[]) {
try (Sample s = new Sample("s")) {
System.out.println(" try");
throw new Exception();
} catch (Exception ex) {
System.out.println(ex);
Throwable[] ts = ex.getSuppressed();
for(Throwable t:ts) {
System.out.println(t);
}
System.out.println(" catch");
} finally {
System.out.println(" finally");
}
}
}
try
s close
java.lang.Exception
java.lang.RuntimeException
catch
finally