Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

...

Code Block
bgColor#FFCCCC
public class Login {
  static void checkPassword(String password_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(password_file));
    // Compare credentials 
     
    } finally {
      reader.close();
      // Other clean-up code 
    }
}

  public static void main(String[] args) throws IOException {
    String path = "password""password";
    checkPassword(path);
  }
}

...

Code Block
bgColor#ccccff
public class Login {
  static void checkPassword(String password_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(password_file));

    try {
      // Compare credentials
    } finally {
        try {    
          // Enclose in try-catch block
          reader.close();
        } catch (IOException ie) {
          // Forward to handler
        }
        // Other clean-up code
    }
  }

  public static void main(String[] args) throws IOException {
    String path = "password";"password";
    checkPassword(path);
  }
}

Compliant Solution (2)

...

Code Block
bgColor#ccccff
public class Login {
  static void checkPassword(String password_file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(password_file));

    try {
      // Compare credentials
    } finally {
      closeIgnoringException(reader);
      // Other clean-up code 
    }
}

  private static void closeIgnoringException(BufferredReader s) {
    if (s != null) {
      try {
        s.close();
      } catch (IOException ie) {
        // Ignore exception if close fails
      }
    }
  }

  public static void main(String[] args) throws IOException {
    String path = "password";"password";
    checkPassword(path);
  }
}

In production systems, it is often better to limit the lifetime of sensitive data by avoiding the use of a BufferedReader. See the guideline MSC08-J. Limit the lifetime of sensitive data for more details.

...

EXC30-J. Do not exit abruptly from a finally block            13. Exceptional Behavior (EXC)            EXC32-J. Catch specific exceptions as opposed to the more general RuntimeException