Java try-with-resource
今天在GitHub上看Netty的Pull requests时,Commits Refactor using try-with-resources statement #11530 变更 try-catch 提交为 try-with-resources,本文就聊一下try-with-resources,以下翻译自try-with-resources 2014 by Joe.。

Java 7 gave us try-with-resources, a nice feature on exception handling. Java7提供的try-with-resources语句,是异常处理的一大利器。
Close the resources in finally block is a well know rule for all java developers. As part of exception handling mechanism, we should always ensure to close and release the resources that is used inside the block. As part of exception handling mechanism, we should always ensure to close and release the resources that is used inside the block. In a block of code which is enclosed in a try-catch block, if an exception is thrown the normal flow is altered. 对所有java开发人员而言,在finally代码块中关闭资源是再熟悉不过的处理方式了。异常处理的一部分工作,就是确保代码块中的各类资源被关闭和有效释放。一旦try-catch语句块中的代码抛出了异常,之前的工作流程就会发生改变。
try {
//code statements
//exception thrown here
//lines not reached if exception thrown
} catch (Exception e) {
//lines reached only when exception is thrown
} finally {
//always executed
//irrespective of an exception thrown or not
}
Look at the above code block. The best place to close and release all the resources is finally block. So what is the resource we are talking about here? Resources means database connection, file connections, etc. 显然,上述代码中,关闭并释放各类资源的最佳位置,就是finally部分。这里提到的资源,就是像数据库连接、文件连接等等这样的具体实例或对象。
Poor Structure 糟糕的结构
As stated above, we are going to close the resources in the finally block. Look at the following code, how ugly it looks like. 如前所述,要在finally语句中关闭资源。来看看下面的代码有多么难看:
...
InputStream is = null;
try {
is = new FileInputStream("test");
is.read();
...
} catch (Exception e) {
...
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
...
}
}
Explicitly the programmer has to close the resource and need to surround it with a try-catch block and all inside the finally. This is a standard repeated code in java projects. 程序员不得不显式地关闭某个资源,并且还要在finally中反复使用try-catch语句来处理这条关闭语句,这是java程序中典型的冗余代码。
Automatic Resource Management (ARM) 资源的自动化管理
In Java 7, we got a nice feature to manage these resources automatically. Manage is really a hype word here, all it does is close the resources. Automatic resource management, helps to close the resources automatically. Java7为我们提供了一个非常强悍的功能来自动关闭这些资源。“管理”一词在这里燃值颇高,其实它的工作就是关闭资源。资源自动化管理帮助我们自动关闭这些资源。
Resource instantiation should be done within try(). A parenthesis () is introduced after try statement and the resource instantiation should happen within that paranthesis as below, 资源的初始化工作是在try()中完成的。try后面引入了一对小括号(),用于在其中完成资源的初始化,示例如下:
try (InputStream is = new FileInputStream("test")) {
is.read();
...
} catch(Exception e) {
...
} finally {
//no need to add code to close InputStream
//it's close method will be internally called
}
try-with-resources and AutoCloseable try-with-resources语句和AutoCloseable接口
- All the classes cannot be used in try-with-resources. AutoCloseable is an interface used as a contract to implement try-with-resources. Classes that implements AutoCloseable must be used as a resource in try-with-resources, else we will get compilation error. 并非所有的类都能用try-with-resources处理。实现AutoCloseable接口是使用try-with-resources语句的前提。在try-with-resources语句中,只有实现了AutoCloseable接口的类才会被视为资源进行相关处理,否则会出现编译错误。
- close is the only method in AutoCloseable and it gets automatically invoked at runtime. lose方法是AutoCloseable接口的唯一方法,该方法在程序运行时会被自动调用。
- Multiple classes can be declared within the same try as “try (Lion lion = new Lion(); Tiger tiger = new Tiger()) {…” 在同一个try语句中可以声明多个资源类,例如:“try (Lion lion = new Lion(); Tiger tiger = new Tiger()) {…”
- During initialization of multiple resources in ‘try’, if there is any issue then immediately in the reverse order those resources that are already initialized will be closed. try中的多个资源在初始化过程中,一旦发生异常,那些已经完成初始化的资源,将按照与其创建时相反的顺序依次关闭。
- When multiple classes are used in ‘try’, then the close method is called in the reverse order. To understand this, check the below example. 若try中用到了多个资源类,则close方法会按照与其声明时相反的顺序依次调用。后面的示例代码对此进行了阐释。
This chapter requires login to view full content. You are viewing a preview.
Login to View Full Content