Java io ugly try-finally block

前端 未结 12 1079
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:57

Is there a not so ugly way of treat the close() exception to close both streams then:

    InputStream in = new FileInputStream(inputFileName);
          


        
12条回答
  •  醉梦人生
    2020-11-28 06:33

    In most cases the 'in' close() exception is irrelevant, so:

        try {
          copy(in, out);
        } finally {
        try {  in.close()  }  catch (Exception e) { /* perhaps log it */ }
        try {  out.close() }  catch (Exception e) {/* perhaps log it */ }
        } 
    

    It's usually bad practice to swallow exceptions, but in this case I think it's ok.

提交回复
热议问题