Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anything I can do when socket.close() throws in Java?

Started learning java a week ago and also decided learning the right way to work with exceptions. Java really drives me mad with the idea of specifying exceptions the method can throw as part of its signature.

I'm currently trying to implement multi-threaded server for client-server application. I was very surprised with the fact socket.close() can throw IOException. The question is, what do I do if it happens?

...
final Socket socket = .... // at this point I know that I have a good socket
try {
  ..... // communicating with someone on that side....
} catch(IOException e) {
  // communication failed
  // this fact is useful, I can log it
  // and will just hang up
} finally {
  try {
    socket.close(); // bye-bye
  } catch(IOException e) {
    // anything but logging I can do here?
  }
}
...

This piece of code is executed within a separate thread, so I just have to catch all the exceptions. The problem is mostly psychological - I know, I can just leave catch block empty, but I'm trying to avoid this trick.

Any thoughts?

like image 946
Andrey Agibalov Avatar asked Aug 10 '11 13:08

Andrey Agibalov


2 Answers

It's quite common that you don't do anything major when closing a resource fails. Logging is probably a good idea, so that you have a chance to find out if it happens more often.

This is different if closing the resource is also the "commit" or in some other way persists the change: then you'd need to treat it just like you would treat an exception in any other part: handle it.

Note that Java 7 has introduced automatic resource management specifically to simplify these kinds of constructs. And if you learn Java now, then I'd suggest going with the latest-and-greatest.

like image 93
Joachim Sauer Avatar answered Oct 12 '22 14:10

Joachim Sauer


I guess it depends if you read data from the socket or wrote data to it. If you read data and retrieved all the info you wanted then you can safely ignore the exception. But if you wrote data you probably have to assume that it did not get transmitted correctly.

like image 42
devconsole Avatar answered Oct 12 '22 16:10

devconsole