为什么最后使用代码而不是代码

为什么这样做

} catch (SQLException sqle) { sqle.printStackTrace(); } finally { cs.close(); rs.close(); } 

而不是这个

 } catch (SQLException sqle) { sqle.printStackTrace(); } rs.close(); cs.close(); 

因为如果在执行try块之后没有代码被抛出, 除非发生exception。 无论try块中发生了什么, finally块总是被执行。

看看你的catch块 – 它会抛出DAOException 。 所以即使在你提供的示例中, catch块之后的语句也不会被执行。 你所显示的(在另一个例外中包含一个exception)是一种常见的模式 – 但另一种可能性是catch块“意外地”抛出一个exception,例如,因为其中一个调用失败。

另外,可能还有其他的例外,你不知道 – 或者是因为你声明了方法抛出它们,或者是因为它们是未经检查的exception。 你真的想泄漏资源,因为IllegalArgumentException被抛出某处?

因为如果抛出exception,

  • finally子句中的代码将在exception向外传播时执行,即使exception中止了方法执行的其余部分。

  • try / catch块之后的代码将不会被执行,除非exception被catch块捕获而不被重新抛出。

因为它确保finally块中的东西被执行。 catch之后的东西可能不会被执行,比如说catch块中有另一个exception,这是非常可能的。 或者你只是做你所做的,抛出一个exception包装原来的exception。

finally关键字保证代码被执行。 在你的底部例子中,closures语句不被执行。 在顶部的例子中,他们被执行(你想要的!)

你的第二种方法不会做'近距离'的陈述,因为它已经离开了方法。

如果你捕获所有的错误,应该没有区别,否则,只有finally块内的代码才会被执行,因为代码执行顺序是:finally代码 – >错误throw – >代码之后,因此,一旦你的代码抛出任何未处理的错误,代码块按预期工作。

这是避免资源泄漏的方法

finally块中的代码将在catch块中重新生成exception之前被调用。 这可以确保你放入finally块的清理代码被调用。 finally块之外的代码将不会运行。

这可能会澄清: http : //www.java2s.com/Code/Java/Language-Basics/Finallyisalwaysexecuted.htm

考虑catch可以抛出一个exception,在调用堆栈中的更高层次的function。 这将导致调用最后一个例外的上级。

http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html这是误导(并可能产生的问题):;

The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.

 1. The new FileWriter statement fails and throws an IOException. 2. The list.get(i) statement fails and throws an IndexOutOfBoundsException. 3. Everything succeeds and the try block exits normally. 

第四种方式 (抛出IOExceptionIndexOutOfBoundsException的exception)缺失。 上一页中描述的代码在最终求助之前仅捕获(1)和(2)。

我也是Java新手,在发现这篇文章之前也有同样的问题。 一般来说,潜在记忆往往更多地关注于例子而不是理论。

finally块可能并不总是运行,请考虑下面的代码。

 public class Tester { public static void main(String[] args) { try { System.out.println("The main method has run"); System.exit(1); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("The finally block has run"); } } } 

在你的情况下,我会build议将代码封装到try / catch中,因为这段代码显然可能会引发exception。

  } catch (SQLException sqle) { sqle.printStackTrace(); } finally { try { cs.close(); rs.close(); } catch (Exception e) { //handle new exception here } 

根据HeadFirst Java,即使try或catch块有返回语句,finally块也会运行。 stream程跳转到最后,然后返回。