Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
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 {
   } finallytry {
    	  if (br != null) {
        	br.close();
        }
        if (bw != null) {
        	bw.close();
      }
    } catch (IOException x) {
      // handle error
    }
  }
}

Compliant Solution (finally block)

This compliant solution uses finally blocks a second finally block to guarantee that both br and bw are properly closed, regardless of any exceptions that may be thrown during the close operationsthat bw is properly closed even if an exception is thrown while closing br.

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
          }
        }
      }
    }
  }
}

...

This compliant solution uses a try-with-resources statement which will guarantee that both br and bw are properly closed, regardless of any exceptions potentially thrown during the close operations.

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
        }
}

Noncompliant Code Example

...