How to properly handle an IOException from close()

前端 未结 9 1569
滥情空心
滥情空心 2021-02-05 08:14

The Java I/O classes java.io.Reader, java.io.Writer, java.io.InputStream, java.io.OutpuStream and their various subclasses al

9条回答
  •  梦毁少年i
    2021-02-05 08:40

    Well, in most cases, close() doesn't actually throw an IOException. Here's the code for InputStream.java:

      public void close() throws IOException
      {
        // Do nothing
      }
    

    Errors from closing a network resource should really be of some type of RuntimeException, since you can disconnect a networked resource after the program connects to it.

    You can see some example of various implementations of Reader/Writer and Streams using Google Code Search. Neither BufferedReader nor PipedReader actually throw an IOException, so I think you're mostly in the safe by not worrying about it. If you're really worried, you can check the implementation of the libraries you're using to see if you ever need to worry about the exception.

    Like others mentioned, you can't do much about the IOException other than log it.

    After all, try/catch blocks in the finally clause are pretty ugly.

    Edit:

    Further inspection reveals subclasses of IOException like InterruptedIOException, SyncFailedException, and ObjectStreamException, along with classes that inherit from it. So just catching an IOException would be too general -- you wouldn't know what to do with the information other than logging it because it could be from a whole range of errors.

    Edit 2:

    Urk, BufferedReader was a bad example, since it takes a Reader as input. I've changed it to InputStream.java

    However, there's a hierarchy with InputStream <= FilterInputStream <= BufferedInputStream <= InputStreamReader (via inheritance and private instances) that all trickle up to the close() method in InputStream.

提交回复
热议问题