Yichuan  Wang
Yichuan Wang

Reputation: 41

How to handle IOException when closing bufferedReader

Hi I am learning about Exceptions in Java and I encountered a problem with this situation.

    public static void main(String[] args){
    String path = "t.txt";
    BufferedReader br = null;
    try{
        br = new BufferedReader(new FileReader(path));
        StringBuilder sbd = new StringBuilder();
        String line = br.readLine();
        while(line != null){
            sbd.append(line);
            sbd.append(System.lineSeparator());
            line = br.readLine();
        }
        String result = sbd.toString();   
        System.out.print(result);
    }catch(IOException e){
        System.out.println(e.getMessage());
    }finally{
        if (br != null) 
            br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
    }
}

when I call method close() to close the bufferedReader, it says unreported exception IOException; must be caught or declared to be thrown.

I know that JAVA 7 provides a pretty easy way to do the clean-up with

 try(br = new BufferedReader(new FileReader(path))){
//.... 
}

but prior to JAVA 7, what can I do with this situation? adding "throws IOException" right next to the main function declaration is a way to fix that but is it a little bit complicated since I have had a catch section to catch IOExceptions

Upvotes: 3

Views: 3988

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

This is approximately how try-with-resources closes resources

    BufferedReader br = new BufferedReader(new FileReader(path));
    IOException ex = null;
    try {
        br.read();
        // ...
    } catch(IOException e) {
        ex = e;
    } finally {
        try {
            br.close(); // close quietly
        } catch (IOException e) {
            if (ex != null) {
                ex.addSuppressed(e);
            } else {
                ex = e;
            }
        }
    }
    if (ex != null) {
        throw ex;
    }

Upvotes: 1

Jason
Jason

Reputation: 11832

I generally code it thus:

} finally {
    if (br != null) {
        try { 
            br.close();
        } catch(IOException ioe) {
            // do nothing
        }
    }
}

In fact, I once wrote a util class containing methods such as closeStream(final InputStream stream), closeStream(final OutputStream stream), closeReader(final Reader reader), etc that hides all this stuff, since you end up using it all the time.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

prior to JAVA 7, what can I do with this situation?

You can add a try-catch in the finally block like,

} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            // Handle the IOException on close by doing nothing.
        }
    }
}

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347204

You wrapped it into another try-catch

}finally{
    if (br != null) 
        try {
            br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
        } catch (Exception exp) {
        }
}

Now, if you care or not is another question. To my mind, your intention here is to make all best effort to close the resource. If you want, you could use flag and set it to true in the parent catch block (indicating that any following errors should be ignored) and if it's false in the close catch block, display an error message, for example...

boolean hasErrored = false;
try {
    //...
}catch(IOException e){
    e.printStackTrace();
    hasErrored = true;
}finally{
    if (br != null) 
        try {
            br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
        } catch (Exception exp) {
            if (!hasErrored) {
                // Display error message...
            }
        }
}

Upvotes: 4

sasankad
sasankad

Reputation: 3613

add another try catch block

 ... 
    if(br != null)
       try{
            br.close();
       } catch (IOException io){
       }

Upvotes: 1

Related Questions