Search code examples
javaexceptiontry-catchbufferedreader

Proper exception handling on closing file read/write operations


What i want is to reduce exceptions to be thrown from a method.
As you can see i have an inner try catch in the outer catch block to avoid the exception be thrown.
Is this the normal way to do this or are there better (more elegant) ways?
Or is this approach completely false and i should just throw the exception?

public static String readText(String filename) {        
    String text = "";
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(filename));
        String line = null;
        while( (line = br.readLine()) != null ){
            text += line;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(br != null)
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    return text;
}

Solution

  • Personally I'd go for a more modern approach with either Files.readAllLines(); or Files.lines();.

    Then all you need to handle is an IOException and the resources are cleaned up for you automatically.