Why write Try-With-Resources without Catch or Finally?

扶醉桌前 提交于 2019-11-30 04:45:26

As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

See this code example

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
               new BufferedReader(new FileReader(path))) {
    return br.readLine();
}
}

In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly.

Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed.

While on the other hand if you are using try-with-resources statement and exception is thrown by both try block and try-with-resources statement then in this case the exception from try-with-resources statement is suppressed.

As the @Aaron has answered already above I just tried to explain you. Hope it helps.

Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

This is a new feature in Java 7 and beyond. Without this, you'd need a finally block which closes the resource PrintWriter out. So the code above is equivalent to:

PrintWriter out = null;
try {
    PrintWriter out = ...
} finally {
    if(null != out) {
        try {
            out.close();
        } catch(Exception e) {} // silently ignore!
    }
}

See The try-with-resources Statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!