在java中尝试使用资源和返回语句

时间:2014-04-08 20:42:51

标签: java return try-with-resources

我想知道在 try-with-resources 块中放置 return 语句是否会阻止资源自动关闭。

try(Connection conn = ...) {
    return conn.createStatement().execute("...");
}

如果我写这样的话会关闭 Connection 吗?在Oracle文档中,声明:

  

try-with-resources语句确保在语句结束时关闭每个资源。

如果由于return语句而从未到达语句的结尾会发生什么?

4 个答案:

答案 0 :(得分:44)

基于Oracle's tutorial,“[资源]将被关闭,无论try语句是正常完成还是突然完成”。它将abruptly定义为异常。

try内返回是JLS 14.1定义的突然完成的示例。

答案 1 :(得分:11)

资源将自动关闭(即使使用C4语句),因为它实现了C5接口。这是一个输出"成功关闭的例子":

return

答案 2 :(得分:0)

AutoCloseable接口可使代码的执行顺序乍一看令人困惑。让我们通过一个示例来完成此操作:

public class Main {

    // An expensive resource which requires opening / closing
    private static class Resource implements AutoCloseable {

        public Resource() {
            System.out.println("open");
        }
        
        @Override public void close() throws Exception {
            System.out.println("close");
        }
    }
    
    // find me a number!
    private static int findNumber() {
        // open the resource
        try(Resource resource = new Resource()) {
            // do some business logic (usually involving the resource) and return answer
            return 2 + 2;
        } catch(Exception e) {
            // resource encountered a problem
            throw new IllegalStateException(e);
        }
    }
    
    public static void main(String[] args) {
        System.out.println(findNumber());
    }
}

上面的代码尝试使用资源打开一些Resource并进行一些业务逻辑(在这种情况下只是一些算术运算)。运行代码将打印:

open
close
4

因此,Resource在退出try-with-resource块之前已关闭。为了弄清楚到底发生了什么,让我们重新组织findNumber()方法。

    private static int findNumber() {
        // open the resource
        int number;
        try(Resource resource = new Resource()) {
            // do some business logic and return answer
            number = 2 + 2;
        } catch(Exception e) {
            // resource encountered a problem
            throw new IllegalStateException(e);
        }
        return number;
    }

从概念上讲,这是将return放在try-with-resource块内时在幕后发生的情况。 return操作移至try-with-resource块之后,以允许AutoCloseable对象在返回之前关闭。

因此,我们可以得出这样的结论,即try-with-resource块中的return操作只是语法糖,您不必担心在AutoCloseable关闭之前返回。

答案 3 :(得分:0)

好的答案已经发布。我只是采取了不同的方法,因为这感觉像是一个深入研究一些可能有一天会派上用场的细节的机会,它试图通过阅读一些字节码来回答问题。

有几个场景 - 看看

  • try 块中的异常
  • 在退出 auto-closeable 块期间关闭 try 时的异常
  • 在处理较早的异常期间 closing auto-closeable 资源时的异常
  • try 块中的 return,在 return 之前执行 close

在 Java 中使用 try-with 时通常会首先想到第一种情况。我们可以尝试通过查看字节码来理解其他三种场景。最后一个场景解决了您的问题。

分解下面 main 方法的字节码

import java.io.*;

class TryWith {

  public static void main(String[] args) {
    try(PrintStream ps = System.out) {
       ps.println("Hey Hey");
       return;
    }
  }
}

让我们小部分回顾一下(省略了一些细节)

    Code:
         0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
         3: astore_1

0:获取静态字段System.out
3:将字段存储到插槽 1 处的 LocalVariableTable (lvt)。

查看 lvt,我们可以确认第一个插槽属于 java.io.PrintStream 并且它的名称为 ps

      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            4      35     1    ps   Ljava/io/PrintStream;
            0      39     0  args   [Ljava/lang/String;
         4: aload_1
         5: ldc           #3                  // String Hey Hey
         7: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V

4:加载 ps (aload_1)
5:从常量池中加载常量(ldc),hey hey
7:调用print line方法,这会消耗操作数栈中的pshey hey

        10: aload_1
        11: ifnull        18
        14: aload_1
        15: invokevirtual #5                  // Method java/io/PrintStream.close:()V
        18: return

10 - 11:将 ps 加载到操作数堆栈中。检查 ps 是否为 null,如果为 null,则从函数跳转到 18return
14 - 18:加载 ps,调用 closereturn

以上内容特别有趣,因为它表明如果 try-with 资源是 Auto-Closeable 而不是 null 异常,throw 块将起作用。当然,即使它确实有效,也没有实际意义——除非在 try 块中没有访问资源。任何访问都会导致 NPE。

以上也是正常流程,万一出现异常怎么办?来看看异常表

      Exception table:
         from    to  target type
             4    10    19   Class java/lang/Throwable
            24    28    31   Class java/lang/Throwable

这告诉我们,字节码 4-10 之间的任何 java.lang.Throwable 类型的异常都在目标 19 处处理。对于第 31 行的第 24-28 行也是如此。

        19: astore_2
        20: aload_1
        21: ifnull        37
        24: aload_1
        25: invokevirtual #5                  // Method java/io/PrintStream.close:()V
        28: goto          37

19:将异常存入局部变量2
20 - 25:这与我们之前看到的相同模式 close 仅在 ps 不是 null 时才被调用 28:跳转到37

的指令
        37: aload_2
        38: athrow

37:在位置2加载局部变量表中存储的对象,之前我们将异常存储在这个位置。
38:抛出异常

但是,当 close 由于较早的异常而执行时,在 close 期间发生异常的情况如何。让我们回顾一下异常表

      Exception table:
         from    to  target type
             4    10    19   Class java/lang/Throwable
            24    28    31   Class java/lang/Throwable

这是异常表的第二行,我们看一下target 31对应的字节码

        31: astore_3
        32: aload_2
        33: aload_3
        34: invokevirtual #7                  // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
        37: aload_2
        38: athrow

31:次要异常存储在槽 3 的局部变量中。
32:从插槽 3 重新加载原始异常。
33-34:将次要异常作为抑制异常添加到原始异常中。
37-38: 抛出新的异常,我们之前介绍过这些行。

重新审视我们在开头列出的考虑事项

  • 在退出 auto-closeable 块期间关闭 try 时的异常。
    ** 引发异常并且 try 块退出 abruptly
  • 在处理较早的异常期间 closing auto-closeable 资源时的异常。
    ** 一个被抑制的异常被添加到原始异常并抛出原始异常。 try 块退出 abruptly
  • 在try块中返回,在返回之前关闭执行。
    ** close 在 try 块中的 return 之前执行

重新审视我们在字节码中遇到的 auto-closeable 资源为 null 的有趣场景,我们可以用

import java.io.*;

class TryWithAnother {

  public static void main(String[] args) {
    try(PrintStream ps = null) {
       System.out.println("Hey Hey");
       return;
    }
  }
}

毫不奇怪,我们在控制台上得到了输出 Hey Hey,没有例外。

最后但非常重要的是要记住,这个字节码是 JLS 的兼容实现。这种方法对于确定您的实际执行需要什么非常方便,可能还有其他兼容的替代方案 - 在这种情况下我想不出任何。但是考虑到这一点,如果不指定我的 javac 版本

,此回复将不完整
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode)
相关问题