简体   繁体   English

死代码警告Java

[英]dead code warning java

I have the following part of code: 我有以下代码部分:

public void deepSearch(File fileToLook,ArrayList<File> fileStorage,DefaultComboBoxModel<String> mod){
        if(fileToLook.isDirectory())
        {
            for(File f:fileToLook.listFiles())
                deepSearch(f,fileStorage,mod);
        }
        else if(fileToLook != null){
            fileStorage.add(fileToLook);
            mod.addElement(fileToLook.getName());
        }
        else
            System.out.println("Reached an end.");
    }

But eclipse gives me a dead code warning on this: 但是eclipse对此给出了无效代码警告:

else
    System.out.println("Reached an end.");

Can you explain why this is happening.Thanks in advance 你能解释为什么会这样吗?

Well, fileToLook can't be null when the else statement is reached, since if it is null , the first condition will throw a NullPointerException . 好吧, fileToLook else语句时, fileToLook不能为null,因为如果为null ,则第一个条件将引发NullPointerException

It would make more sense to refactor the method, and avoid the potential NullPointerException : 重构该方法会更有意义,并避免潜在的NullPointerException

if(fileToLook != null) {
    if(fileToLook.isDirectory()) {
        for(File f:fileToLook.listFiles())
            deepSearch(f,fileStorage,mod);
    } else {
        fileStorage.add(fileToLook);
        mod.addElement(fileToLook.getName());
    }
} else {
    System.out.println("Reached an end."); // not sure if you really need this
                                           // statement. It looks like a debug print to me
}

Well the null if (fileToLook != null) check is actually not needed, because if (fileToLook.isDirectory()) already throws a NullPointerException if it is null. 那么实际上就不需要null if (fileToLook != null)检查,因为if (fileToLook.isDirectory())如果已经为null,则已经引发了NullPointerException。 The last else can thus never be reached. 因此,永远无法达到最后的其他。

The first if condition will throw a NullPointerException if fileToLook is null. 如果fileToLook为null,则第一个if条件将引发NullPointerException The second branch is taken if it's not null. 如果第二个分支不为null,则采用它。 Therefore the third branch is never executed. 因此,永远不会执行第三个分支。

You might want to put the null check first. 您可能想先将空检查放在首位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM