For the acquisition and shutdown of resources, such as files, JDBC, programmers need to manually shut down resources, such as Close,shutdown. If the resource is turned off improperly, a resource leak will occur.
Example 1:
public static Properties loadpropertiesbadly (String fileName)
throws IOException {
FileInputStream stream = new FileInputStream (fileName);
Properties Props = new properties ();
Props.load (stream);
Stream.Close ();
return props;
}
Fortunately, there is a potential resource leak in this example. If all goes well, the stream will be closed before the method returns. However, if the Props.load () method throws a IOException, the stream is not closed (until the garbage collector runs its finalizer). The solution is to use the try...finally mechanism to ensure that the stream is closed, regardless of whether an error occurred.
Example 2:
public static Properties loadproperties (String fileName)
throws IOException {
FileInputStream stream = new FileInputStream (fileName);
try {
Properties props = new properties ();
Props.load (stream);
return props;
}
finally {
stream.close ();
}
}
Note that resource fetching (open file) is done outside a try block, and if you put it in a try block, the finally block runs even if the resource fetch throws an exception. Not only is this method inappropriate (you cannot release resources that you do not have), the code in finally blocks can also throw its own exceptions, such as NullPointerException. The exception thrown from the finally block replaces the exception that caused the block to exit, which means that the original exception was lost and cannot be used to help with debugging.
Example 3:
public void Enumeratefoo () throws SQLException {
Statement Statement = null;
ResultSet ResultSet = null;
Connection Connection = getconnection ();
try {
statement = connection.createstatement ();
ResultSet = Statement.executequery ("SELECT * from Foo");
Use ResultSet
}
finally {
if (resultSet!= null)
resultset.close ();
if (statement!= null)
statement.close ();
Connection.close ();
}
The reason this "solution" is unsuccessful is that the close () method of the ResultSet and Statement can throw the SQLException itself, which causes the close () statement in the later finally block to execute. You have several options here, and each one is annoying: use a try ... The catch block encapsulates each close (), nesting try...finally blocks like Listing 4, or writing a small framework to manage resource acquisition and release