java解除引用可能的空指针

1 java null

在我的代码中,我收到了上述警告.这是我得到它的代码的一部分,

try {
        fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    } catch (URISyntaxException | NullPointerException e) {
    }
    finally {
        if (fileFile.getPath()!= null){
            strPathName = fileFile.getPath();
        }
        if (fileFile.getName() != null){
            strFileName = fileFile.getName();
        }
    }  
Run Code Online (Sandbox Code Playgroud)

该行if (fileFile.getPath()!= null){是带警告的行.此代码不是Main类的一部分.它位于同一包中另一个类文件的另一个类中.

我对编程不是很有经验,但我相信我做了几乎所有事情来阻止或捕获空指针异常.为什么我仍然得到它,我该怎么做才能摆脱它?谢谢你的帮助.

阅读完所有提示后,我解决了它.这是完整的代码:

public static ArrayList<String> getCurrentPath() {

    File fileFile;
    String strPathName, strFileName;
    ArrayList<String> arrPathFileName;

    strFileName = null;
    strPathName = null;

    try {
        fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        if (fileFile.getPath()!= null){
            strPathName = fileFile.getPath();
        }
        if (fileFile.getName() != null){
            strFileName = fileFile.getName();
        }
    } catch (URISyntaxException use) {
    }     
    arrPathFileName = new ArrayList<>(); 
    arrPathFileName.add(strPathName);
    arrPathFileName.add(strFileName);

    return arrPathFileName;
}
Run Code Online (Sandbox Code Playgroud)

如前所述,我只是将if语句放入try块并删除finally块.

BTW也试图将两个块组合成一个方式:

if (fileFile != null){
            strPathName = fileFile.getPath();
            strFileName = fileFile.getName();
        }
Run Code Online (Sandbox Code Playgroud)

但是这产生了一个警告,即fileFile永远不会变为null.(从一开始我的观点是什么,因此警告"取消引用可能的空指针"真的让我感到困惑.)

Bri*_*new 10

因此,如果您在第一行引发异常,则您的变量将不会分配给a File,并将保留其之前的值(null如果之前未分配).捕获您的异常,然后继续使用该未分配的变量.因此警告.请参阅下面的注释代码.

try {
        fileFile = // exception thrown. Variable not assigned
} catch (URISyntaxException | NullPointerException e) {
        // exception caught
    }
    finally {
       // unassigned variable used here...
        if (fileFile.getPath()!= null){
            strPathName = fileFile.getPath();
        }
        if (fileFile.getName() != null){
            strFileName = fileFile.getName();
        }
    }  
Run Code Online (Sandbox Code Playgroud)

如果可行的话,我宁愿使用try块中的范围并使用变量.在你的finally块中,你需要尽可能小心,因为你可以从try块中的大多数地方来到它.

顺便说一下,这个:

Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
Run Code Online (Sandbox Code Playgroud)

如果你得到NPE会给你带来很大的问题.上面哪个解决了null?我可能会更明确,这样您就可以检查每次调用的空值,并明确地确定哪个调用给了您一个null.Tiresome?不幸的是.