Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
public void processFile(String inPath, String outPath) throws IOException {
  BufferedReader br = null;
  BufferedWriter bw = null;
  try {
    br = new BufferedReader(new FileReader(inPath));
    bw = new BufferedWriter(new FileWriter(outPath));
    // ... process the input and produce the output
  } finally {
    if (br != null) {
      try {
        br.close();
      } catch (IOException x) {
        // handle error
      } finally {
        if (bw != null) {
          try {
            bw.close();
          } catch (IOException x) {
            // handle error
          }
        }
      }
    }
  }
}

Compliant Solution (Java 7, try-with-resources)

This compliant solution uses a try-with-resources statement (introduced in Java 7) to manage both br and bw.  

Code Block
bgColor#ccccff
public void processFile(String inPath, String outPath) throws IOException{
  try (BufferedReader br = new BufferedReader(new FileReader(inPath));
       BufferedWriter bw = new BufferedWriter(new FileWriter(outPath));) {
    // process the input and produce the output
  } catch (IOException ex) {
    System.err.println("thrown exception: " + ex.toString());
    Throwable[] suppressed = ex.getSuppressed();
    for (int i = 0; i < suppressed.length; i++) {
      System.err.println("suppressed exception: " + suppressed[i].toString());
    }
  }
}

...