Advertise here!

Close your Streams

All right, so this post isn't for most programmers out there. It is, however, meant for any new Java programmers, or just really aloof ones.

I work at a large Fortune 500 company as a contractor. We're working on a project in Java that is now on about it's 4th or 5th year of life.

One of my co-workers, who's been working on the project for at least 3 years now had the following code in one of her classes:

try {
  Connection conn = getConnection(url);
  Request req = new Request(message);
  Response resp = conn.sendMessage(req);
  if (resp == null || resp.isErrorCode()) {
    sendFailure();
  } else {
    sendSuccess();
  }
  conn.close();		           			
} catch (IOException e) {
  e.printStackTrace();		           		
}	

See the problem?

Exactly. She didn't close her socket in a finally clause. That means if we do get an Exception, the socket might never be closed properly.

She should have done something like this:

Connection conn = null;
try {
  conn = getConnection(url);
  Request req = new Request(message);
  Response resp = conn.sendMessage(req);
  if (resp == null || resp.isErrorCode()) {
    sendFailure();
  } else {
    sendSuccess();
  }           			
} catch (IOException e) {
  e.printStackTrace();		           		
} finally {
  try {
    // always properly close the connection
    if(conn != null) conn.close();
  } catch (CommException e) {
    // ignore
  }
}			

Just another reason why Ruby is nicer. Using the block form of IO.open ensures that the stream will always get closed, and that we don't have to do all sorts of double-wrapping with try-catch code.

Posted at 3pm on 07/15/05 | Posted in , , | no responses | read on

Older posts: 1 2 3