在我的代码中,我收到了上述警告。这是我得到的代码部分,
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();
}
}
行 if (fileFile.getPath()!= null){
是带有警告的行。
此代码不是主类的一部分。它在同一包中另一个类文件的另一个类中。
我在编程方面不是很有经验,但我相信我几乎做了所有事情来防止或捕获空指针异常。为什么我仍然得到它,我该怎么做才能摆脱它?感谢您的帮助。
在阅读了您的所有提示后,我解决了它。完整代码如下:
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;
}
如前所述,我只是将 if 语句放入 try block 并删除了 finally block 。
BTW 也尝试以这种方式将两个 if block 组合成一个:
if (fileFile != null){
strPathName = fileFile.getPath();
strFileName = fileFile.getName();
}
但这会产生一个警告,即 fileFile 永远不会变为 null。 (从一开始我的观点是什么,所以警告“解引用可能的空指针”让我很困惑。)
最佳答案
因此,如果您在第一行抛出异常,您的变量将不会分配给 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();
}
}
如果可行的话,我宁愿在 try block 中限定和使用变量。在您的 finally block 中,您需要尽可能地小心,因为您可以从 try block 中的大多数地方到达它。
顺便说一句,这个:
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
如果您确实获得了 NPE,将会给您带来巨大的问题。以上哪项解析为 null ?我可能会更明确,这样您就可以检查每次调用的空值并明确确定哪个调用给了您空值。累吗?不幸的是。
关于java取消引用可能的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966988/