public void enumerateBar() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM Bar");
// Use resultSet
}
finally {
try {
if (resultSet != null)
resultSet.close();
}
finally {
try {
if (statement != null)
statement.close();
}
finally {
connection.close();
}
}
}
}
private Connection getConnection() {
return null;
}
|
我们都知道应该使用 finally 来释放像数据库连接这样的重量级对象,但是我们并不总是这样细心,能够记得使用它来关闭流(毕竟,终结器会为我们做这件事,是不是?)。很容易忘记在使用资源的代码不抛出已检查的异常时使用 finally。清单 5 展示了针对绑定连接的 add() 方法的实现,它使用 Semaphore 来实施绑定,并有效地允许客户机等待空间可用:









