-1

I'm currently working on a simple method which converts the content of a file to a string. I saw several topics covering some detail about this question (here). However I can use the try catch or a return do_nothing as mentioned in the previous linked answer. The code:

public static String getStringFromFile(String path) throws EmptyFileException {
    String data =null; 

    try {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line;
        while ((line = reader.readLine()) != null) {
            data += line +"\n";
        }
        if (data == null) {
            throw new EmptyFileException();
        }

    }

    catch (FileNotFoundException ex) {
            showExceptionMessage("File not found");
    } 
    catch (IOException ex) {
        showExceptionMessage("Can't read the file");
    }

    return(data);

}

private static void showExceptionMessage(String message) {
    JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
}

So what would be "better" throwing an exception if the file is empty or just using return doNothing() (were doNothing is the function that does nothing, makes sense right? hahah).

Community
  • 1
  • 1
  • From an application point of view, is it OK to handle a missing file, empty file and bad read as a general "no message found" situation that results in a "do nothing" flow? Or put another way, do you only want to show a message if it was found in the file, otherwise show nothing (even if there was an error typing to get the message from the file)? – Bohemian Oct 31 '16 at 20:33

1 Answers1

0

Is this a good way to avoid null return?

Yes, always return "existing" object instead of null if you can. Null Object Pattern is a good aproach to avoid that.

So what would be "better" throwing an exception if the file is empty or just using return doNothing()

In your case throwing an exception is overkill for me. You should throw an exception when you don't expect particular behaviour. Have a look at FileNotFoundException. You always expect that file exists so it's a good choice to throw exception when you can't find this file.

So as metioned above null is bad, so why can't you return empty string? :) In this case it will work like Null Object Pattern, like placeholder :)

  • I was thinking it would be strange to return an empty string because the user/programmer would expect the file to contain at least something (otherwise it would be useless to convert the data to a string)? – Bioinformatician Oct 31 '16 at 20:23