I write to socket with:
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
But this can throw IOException, so I do:
try {
OutputStream socketStream = socket.getOutputStream();
socketStream.write(buf);
} catch (IOException e) {
// logging
} finally {
socket.close();
}
-
But
socket.closealso force me to catchIOException! So do I needtry ... catchit again infinally? -
When catch
IOExceptionfromclose, it mean socket not closed? So trycloseagain? Or what to do?
Thanks
close()throwsIOExceptionbecause closing something usually implies callingflush(), and flushing might fail. For example, if you lose network connectivity and issuesocket.close(), you cannot flush whatever you have buffered, soflush()will throw an exception. Because data might be lost, the exception is checked, so you are forced to deal with that possibility.I think the best way to deal with this is:
This code will work normally in the common case. If something goes wrong (even inside
close()), it will allow you to catch the exception and do something before unconditionally closing your socket and swallowing everything it might throw.