这是避免null返回的好方法吗?

时间:2016-10-31 19:54:54

标签: java exception exception-handling null

我目前正在研究一种将文件内容转换为字符串的简单方法。我看到几个主题涉及这个问题的一些细节(here)。但是,我可以使用上一个链接答案中提到的try catch或return do_nothing。代码:

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

那么,如果文件是空的或只是使用return doNothing(),那么抛出异常将会“更好”(doNothing是什么都不做的功能,这是正确的吗?哈哈)。

1 个答案:

答案 0 :(得分:0)

  

这是避免空值返回的好方法吗?

是的,总是返回"现有"如果可以的话,而不是null。空对象模式是避免这种情况的好方法。

  

那会是什么"更好"如果文件为空则抛出异常   或者只是使用return doNothing()

在你的情况下,抛出异常对我来说太过分了。当您不期望特定行为时,您应该抛出异常。看看FileNotFoundException。您总是希望该文件存在,因此当您无法找到此文件时,抛出异常是一个不错的选择。

所以如上所述,null很糟糕,为什么你不能返回空字符串? :)在这种情况下,它将像Null对象模式一样工作,如占位符:)