是否有任何功能差异?

Connection c = null;
try {
  c = getConnection();
  c.doStuff();
} finally {
  if (c!=null) c.close();
}

vs的

Connection c = null;
c = getConnection();
c.doStuff();
try {
} finally {
  if (c!=null) c.close();
}

vs的

Connection c = null;
try {
  c = getConnection();
} finally {
  if (c!=null) c.close();
}
c.doStuff();

我觉得他们所有人都会在所有情况下做同样的事情

有帮助吗?

解决方案

发生在a之外的异常 try-finally 块根据定义是 未处理的异常.在这种情况下,您无法保证操作系统或运行时将如何处理它。很有可能一个异常结束不会被触发,你的代码会简单地中止(也许abend在这个讨论中更好地描述了它-"异常结束"),并且你的 finally 块永远不会执行。

的点 try-finally 是为了保证代码清理发生,并且发生在正确的上下文中。

你一定在想 finally 不管发生什么,块总是会执行,并且它会在整个方法完成后执行,因此其他代码是位于 try-finally 构造,但这是不正确的。

所以如果你想要任何正确行为的运行时保证,你的第一个例子是唯一正确的。

  • 在你的第一个例子中,你获得了更重要的是 使用方法try 块。如果异常发生在 try 块,则该 finally block将执行并关闭您的连接。

  • 在你的第二个例子中,你的连接是完全在 try-catch 构造。如果使用连接发生异常,很可能整个上下文将被抛出,您的 finally block不会执行,您的连接也不会关闭。

  • 在你的第三个例子中, finally 之后会执行 try, ,但在之后的任何代码之前 finally 块。您将生成一个尝试使用该连接的异常,因为该连接已被显式关闭。

其他提示

CRAIG已经解决了未处理的异常问题,但我想明确。我编写了两个例子(最后一个只是糟糕,因为你可以在发生异常后使用破碎的连接,不这样做)。这是一个简单的例子,它抛出了arrayIndexoutofBoundsexception:

class TryCatchFinally {
    static int [] array = new int[1];
    public static void main(String [] args) throws Exception {
        if (args[0].startsWith("1")) {
            version1();
        } else if (args[0].startsWith("2")) {
            version2();
        }
    }
    static int version1() {
        int r = 0;
        try {
            System.out.println("In Try.");
            return array[1];
        } catch (Exception e) {
            System.out.println("In Catch.");
        } finally {
            System.out.println("In Finally.");
        }
        System.out.println("In Return.");
        return r;
    }
    static int version2() {
        int r = array[1];
        try {
            System.out.println("In Try.");
        } catch (Exception e) {
            System.out.println("In Catch.");
        } finally {
            System.out.println("In Finally.");
        }
        System.out.println("In Return.");
        return r;
    }
}
.

和这里是执行:

(TryCatchFinally)$ javac *.java
(TryCatchFinally)$ java TryCatchFinally 1
In Try.
In Catch.
In Finally.
In Return.
(TryCatchFinally)$ java TryCatchFinally 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at TryCatchFinally.version2(TryCatchFinally.java:24)
    at TryCatchFinally.main(TryCatchFinally.java:7)
(TryCatchFinally)$
.

正如您在第一个版本中看到的,则注册异常处理程序,因为异常发生在Try块的上下文中。在第二个版本中,没有注册的异常处理程序,并调用默认异常处理程序(意味着未捕获的异常)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top