wuchang
wuchang

Reputation: 3069

How can I close a BufferedReader after an exception happed?

Take a simple code as an example:

            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(); 
                }
            }

both producer = new LogProducer(); and (line = dr.readLine()) may throw exceptions. So ,my question is , if producer = new LogProducer(); throw an exception, I want to close the BufferedReader properly, what's the appropriate approach? If I put dr.close() in catch clause or finally clause, it forces me to throw an exception again,obviously this is not a good solution.

Upvotes: 0

Views: 58

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could do it the same way you currently close the producer (in the finally block) (and add a try-catch if you don't want to re-throw IOException) like

} finally {
    if(producer != null){
        producer.close(); 
    }
    if(dr != null) {
        try {
            dr.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Or, you could use the try-with-resources statement to close like

try (FileInputStream fis = new FileInputStream("D:\\acc_cp.log");
    BufferedReader dr = new BufferedReader(new InputStreamReader(fis));
    LogProducer producer = new LogProducer()) {
    // ...

Upvotes: 2

Related Questions