如何在异常发生后关闭BufferedReader?

时间:2015-03-27 03:43:43

标签: java exception

以一个简单的代码为例:

            FileInputStream fis = null;
            BufferedReader dr = null;
            try{
                fis = new FileInputStream("D:\\acc_cp.log");
                dr = new BufferedReader(new InputStreamReader(fis));
                producer = new LogProducer(); // it may throw an exception
                String line = "";
                while((line = dr.readLine())!= null ){ // readline may throw an exception too
                     producer.send("test", line);
                     Thread.sleep(50);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(producer != null){
                    producer.close(); 
                }
            }

producer = new LogProducer();(line = dr.readLine())都可能会抛出异常。所以,我的问题是,如果producer = new LogProducer();抛出异常,我想正确关闭BufferedReader,这是什么方法? 如果我将dr.close()放在catch子句或finally子句中,它会强迫我再次抛出异常,显然这不是一个好的解决方案。

1 个答案:

答案 0 :(得分:2)

您可以按照当前关闭producer(在finally区块中)的方式执行此操作(如果您不想重新投掷,请添加try-catch {{ 1}})喜欢

IOException

或者,您可以使用try-with-resources statement} finally { if(producer != null){ producer.close(); } if(dr != null) { try { dr.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } 之类的

close