How to properly handle an IOException from close()

前端 未结 9 1587
滥情空心
滥情空心 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条回答
  •  时光取名叫无心
    2021-02-05 08:51

    Ignoring or just logging is usually a bad idea. Even though it is true that you cannot recover from it, I/O exceptions should always be handled in a unified manner to make sure your software behaves in a unified way.

    I would at least suggest handling like below:

    //store the first exception caught
    IOException ioe = null;
    Closeable resource = null;
    try{
      resource = initializeResource();
      //perform I/O on resource here
    }catch(IOException e){
      ioe = e;
    }finally{
      if (resource != null){
        try{
          resource.close();
        }catch(IOException e){
          if(null == ioe){
            //this is the first exception
            ioe = e;
          }else{
            //There was already another exception, just log this one.
            log("There was another IOException during close. Details: ", e);
          }
        }
      }
    }
    
    if(null != ioe){
      //re-throw the exception to the caller
      throw ioe;
    }
    

    The above is pretty verbose but works well, because it will prefer the IOException during I/O on the resource to the one during close, since it is more likely to contain information of interest to the developer. The code will also throw an IOException when something goes wrong, so you get a unified behaviour.

    There might be nicer ways of doing it, but you get the idea.

    Ideally, you would create a new exception type that would allow storing sibling exceptions, so in case you get two IOExceptions you could store them both.

提交回复
热议问题