开发者

a question about closing a stream/socket in java

when does the methods socket.close() and someStream.close() throws IOException? an开发者_运维百科d how can I solve the problem?

thanks benny.


Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

While closing a readonly stream can't throw, java's IO framework can't check for that as it doesn't have statically checked read vs. write streams


What you should do really depends on your application. For example, if it is a GUI application and the user tried to save a file, you probably want to notify the user and give her a chance to save the file somewhere else. Sometimes it may also make sense to try again to execute the operating a second time before reporting an error to the user. Otherwise, report an error and either move on or abort the program, depending on whether it makes sense to continue or not.


This SO question discusses the situations in which close() may throw an exception. Actually, there are quite a few of them.

Generally speaking there is not much you can do to fix the problem. However you may need to take some recovery action. For example:

  • If you were writing a critical file, and the close() failed, then your application should take steps to ensure that it doesn't clobber the "good" copy of the file with the new copy of file it was writing.

  • If you were writing a request or response using a network socket, maybe you should note that the request/response may not have been sent, so that you can resend it after the connection has been re-established.

Of course it is generally a good idea to report / log the "failure" as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜