【发布时间】:2015-11-05 04:00:47
【问题描述】:
在我的代码中,我收到了上述警告。这是我得到它的代码部分,
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){ 行是带有警告的行。
此代码不是 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;
}
如前所述,我只是将 if 语句放入 try 块并删除 finally 块。
顺便说一句,还尝试将两个 if 块合并为一种方式:
if (fileFile != null){
strPathName = fileFile.getPath();
strFileName = fileFile.getName();
}
但这会产生一个警告,即 fileFile 永远不会变为 null。 (从一开始我的观点是什么,所以警告“取消引用可能的空指针”真的让我很困惑。)
【问题讨论】:
-
catch (URISyntaxException | NullPointerException e) {}??? -- 永远不要这样做 x 2. 认真的。您是 1) 试图捕获一个永远不应该完成的 NPE - 可能具有这些的代码是损坏的代码并且需要修复,并且 2) 您忽略了 catch 块。请尽快阅读异常处理。 -
1. `catch (URISyntaxException | NullPointerException e) {}' 是 Netbeans 在我为每个异常设置单独的 catch 子句时所建议的。
-
这与 NetBeans 没有任何关系,并且再次与 1) NEVER 捕获 NullPointerExceptions,以及 2) NEVER 忽略带有空的异常catch 块(有一些例外)。我坚持我之前的建议:立即阅读有关异常的教程。
-
1) 我完全同意,程序代码永远不会导致 NPE。这就是为什么我为 NPE 添加了一个额外的 catch 块,Netbeans 建议将它与 URISyntaxException catch 块结合使用,但我的主要目标是以不会发生 NPE 的方式编写代码。 2)你是对的,当仔细考虑时,很明显我添加到 finally 块中的内容使 catchblock 无用。我在 catch 块中有一个 printStackTrace 命令。但 Netbeans 再次建议将其删除。谢谢你的评论。这是朝着正确方向迈出的一小步。
-
@Mike NetBeans 可能建议将这两个 catch-blocks 组合起来,因为它们没有做任何不同的事情。此外,在没有
NullPointerExceptions 的情况下,捕获NullPointerException不是编写代码的正确方法(从外观上我可以看出你可能只是试图修复警告)。