0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

try with resource, AutoCloseable

Last updated at Posted at 2023-02-14

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?