Re: More Finally
RedGrittyBrick wrote:
Given this code ...
String driver = "jdbc:myDriver:wombat";
String id = "myLogin";
String pw = "myPassword";
String sql = "select name, phone from contact";
Connection connection = DriverManager.getConnection(driver, id, pw);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String name = resultSet.getString(1);
String phone = resultSet.getString(2);
System.out.println(name + ": " + phone);
}
resultSet.close();
statement.close();
connection.close();
All statements after the first four can throw SQLException, three lots
of resources are potentially allocated (connection, statement and
resultSet).
Sun's examples[1] put those statements into a single try block with no
finally clause and don't really attempt to release local or server
resources.
So far as I can see, to have the resource releasing code in a finally
block would require at three nested try/catch/finally structures - one
for each resource we want to close if it is open.
Assuming that the other parts of this application can usefully continue
if this particular function fails, what is the best way to use
try/catch/finally?
There is an alternative approach in which each variable is declared
outside a single try-catch-finally, with initial value null. In the
finally block there are multiple pieces of code of the form:
if(something != null){
// clean up something
}
Patricia