Question about closing a stream / socket in java

when do socket.close () and someStream.close () methods throw an IOException? and how can i solve the problem?

thanks Benny.

+4
source share
3 answers

Not checking the return value of close () is a common, but nonetheless serious programming error. It is possible that errors in the previous write operation (2) are first reported at the last close (). Do not check the return value when closing the file can lead to silent data loss. This is especially true with NFS and disk quota.

When closing a stream, readonly cannot be selected, the IO java infrastructure cannot check this, because it does not statically check the reading and writing of streams

+2
source

What you have to do really depends on your application. For example, if this is a GUI application, and the user tried to save the file, you probably want to notify the user and let her save the file elsewhere. Sometimes it may also make sense to retry the operation a second time before reporting the error to the user. Otherwise, report an error and either go or interrupt the program, depending on whether it makes sense to continue or not.

+2
source

This SO question discusses situations in which close() may throw an exception. In fact, there are quite a lot of them.

Generally speaking, you cannot do this to fix this problem. However, you may need some recovery. For instance:

  • If you write a critical file and close() fails, then your application should take steps to make sure that it does not compress the “good” copy of the file with a new copy of the file. wrote.

  • If you are writing a request or response using a network socket, you may need to notice that the request / response has not been sent so that you can resend it after the connection has been restored.

Of course, as a rule, it’s nice to also report and record a “failure”.

0
source

Source: https://habr.com/ru/post/1312851/


All Articles