gpt4 book ai didi

java - 返回 null 的方法导致 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 06:16:20 28 4
gpt4 key购买 nike

我写了这个方法:

@Override
protected String call() {
if (list != null) {
int s = list.size();
Metadata metadata;
for (int i = 0; i < s; i++) {
try {
File f = list.get(i);
metadata = ImageMetadataReader.readMetadata(f);
// obtain the Exif directory
ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
// query the tag's value
Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: " + sdf.format(date));
} else {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}

} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error: " + ex.getLocalizedMessage());
} finally {
updateProgress(i + 1, s);
}
}
}
return null;
}

方法directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL)有时会返回null: Source

问题是,通过调用该方法,java 会抛出空指针异常,因此我无法使用 date!=null 来测试它。 NetBeans 还报告“取消引用可能的空指针”提示。我不明白为什么会发生这种情况。为什么我无法在某些对象中存储空值并对其进行测试?即使我不将值存储在变量中,该方法在返回 null 时仍然会导致相同的异常。

最佳答案

此问题的一种解决方案是对 NullPointerException 使用另一个 catch 语句,然后调用在 Date 为 null 时要调用的代码。您还必须将变量“File f”移出 try 语句 block 以确保在 catch 中进行访问。

示例,

catch(NullPointerException e) {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}

关于java - 返回 null 的方法导致 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23656365/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com