Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
String inPath = ...; // input file path
String outPath = ...; // output file path

BufferedReader br = null;
BufferedWriter bw = null;
try {
  br = new BufferedReader(new FileReader(inPath));
BufferedWriter  bw = new BufferedWriter(new FileWriter(outPath));

try {
      // process the input and produce the output
} finally {
    } finallyif (br != null) {
      br.close(br);
  }
  if (bw != null) {
    bw.close(bw);
  }
}

Compliant Solution

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

Code Block
bgColor#ccccff
String inPath = ...; // input file path
String outPath = ...; // output file path

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

...

Code Block
bgColor#FFcccc
String inPath = ...; // input file path

BufferedReader br = null;
try {
  br = new BufferedReader(new FileReader(inPath));

try {

      // process the input and produce the output
} finally {
  if (br }!= finallynull) {
    br.close(br);
  }
}

Compliant Solution

 

This compliant solution uses a try-with-resources statement which will pass on any exception thrown during the processing of the input while still guaranteeing that br is closed.

Code Block
bgColor#ccccff
String inPath = ...; // input file path

try (
      BufferedReader br = new BufferedReader(new FileReader(inPath));
    ) {

       // process the input and produce the output

}

Applicability

Failing to use a try-with-resources statement when dealing with closeable resources may result in some resources not being closed, or important exceptions being masked, possibly resulting in a denial of service attack.

...