Java Reference
In-Depth Information
The problem occurs if an exception is thrown while you're trying to read data from the
connection's input stream. In this case, execution jumps down to the exception handler, and
the input stream and connection are never closed. In a J2SE environment, with memory to
burn, this is probably not a big deal. But on a MIDP device, a hanging connection could be a
disaster. When you absolutely, positively want to be sure to run some code, you should put it
in a
finally
block like this:
HttpConnection hc = null;
InputStream in = null;
try {
hc = (HttpConnection)Connector.open(url);
in = hc.openInputStream();
// Read data from in.
}
catch (IOException ioe) {
// Handle the exception.
}
finally {
try {
if (in != null) in.close();
if (hc != null) hc.close();
}
catch (IOException ioe) { }
}
This is starting to look a little ugly, particularly the
try
and
catch
inside our
finally
block.
A cleaner solution would be to enclose this code in a method and declare that the method
throws
IOException
. This cleans up the code considerably:
private void doNetworkStuff(String url) throws IOException {
HttpConnection hc = null;
InputStream in = null;
try {
hc = (HttpConnection)Connector.open(url);
in = hc.openInputStream();
// Read data from in.
}
finally {
if (in != null) in.close();
if (hc != null) hc.close();
}
}
The deal with
finally
is that its code gets executed no matter how control leaves the
try
block.
If an exception is thrown, or if somebody calls
return
, or even if control leaves the
try
block
normally, our
finally
block still gets executed. Note that there is still a small amount of room
for trouble here: if an exception is thrown when we try to close
in
, then
hc
will never be closed.
You could enclose each
close()
call in its own
try
and
catch
block to handle this problem.
Search WWH ::
Custom Search