属于Java7的新特性。
经常会用try-catch来捕获有可能抛出异常的代码。如果其中还涉及到资源的使用的话,最后在finally块中显示的释放掉有可能被占用的资源。
但是如果资源类已经实现了AutoCloseable这个接口的话,可以在try()括号中可以写操作资源的语句(IO操作),会在程序块结束时**自动释放掉占用的资源**,不用再在finally块中手动释放了。
例子:
没使用该特性
如果要释放的资源多得话,判断加catch占得篇幅大,不美观也不精简
用了这个特性后代码可以精简些
try-catch-finally
try-with-resources
----------------------------------------------------分割线---------------------------------------------------------------------
取自:https://jenkov.com/tutorials/java-exception-handling/try-with-resources.html
Using Multiple Resources
You can use multiple resources inside a Java try-with-resources block and have them all automatically closed. Here is an example of using multiple resources inside a try-with-resources block:
This example creates two resources inside the parentheses after the try keyword. An FileInputStream and a BufferedInputStream. Both of these resources will be closed automatically when execution leaves the try block.
Closing Order
The resources declared in a Java try-with-resources construct will be closed in reverse order of the order in which they are created / listed inside the parentheses. In the example in the previous section, first the will be closed, then the FileInputStream.
Custom AutoClosable Implementations
The Java try-with-resources construct does not just work with Java’s built-in classes. You can also implement the java.lang.AutoCloseable interface in your own classes, and use them with the try-with-resources construct.
The AutoClosable interface only has a single method called close(). Here is how the interface looks:
Any class that implements this interface can be used with the Java try-with-resources construct. Here is a simple example implementation:
The doIt() method is not part of the AutoClosable interface. It is there because we want to be able to do something more than just closing the object.
Here is an example of how the MyAutoClosable is used with the try-with-resources construct:
Here is the output printed to System.out when the method myAutoClosable() is called:
As you can see, try-with-resources is a quite powerful way of making sure that resources used inside a try-catch block are closed correctly, no matter if these resources are your own creation, or Java’s built-in components.
举例
参考:
Java必须懂的try-with-resources
java知识大全
jenkov.com