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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With