为什么抛出NullPointerException?

时间:2014-10-05 22:18:23

标签: java debugging nullpointerexception

我正在试着弄清楚为什么我在这段代码中得到NullPointerException

以下是相关的代码段。

(主)

...

    try (RawData setupData = new RawData(
            new File(fileName), log);) {

        while (true) {

            record = setupData.nextRecord();
            if (record == null) 
                break;

            System.out.println(record.getCountryCode());
            System.out.println(record.getCountryID());
            table.put(record);
            index.put(record);

            count++;

        }


    } catch (IOException e) {

        e.printStackTrace();

    } 

...

(放方法)

public void put(DataTableRecord country) {

    this.current = country;

    try {

        this.file.seek(this.current.getCountryID() * RECORD_SIZE);
        if (!exists(this.current.getCountryID())) {

            writeExternal(this.current);
            this.size++;
            if (country.getCountryID() > this.last)
                this.last = country.getCountryID();

        }

    } catch (IOException e) {

        e.printStackTrace();

    } 

}

(writeExternal方法)

private void writeExternal(DataTableRecord data) throws IOException {

    System.out.println(data.getCountryCode());
    this.file.writeUTF(data.getCountryCode());
    this.file.writeShort(data.getCountryID());
    this.file.writeUTF(data.getName());
    switch (data.getContinent()) {

    case AFRICA :
        this.file.writeShort(1);
        break;

    ...

    case SOUTH_AMERICA :
        this.file.writeShort(7);
        break;

    }

    this.file.writeInt(data.getArea());
    this.file.writeLong(data.getPopulation());
    this.file.writeFloat(data.getLifeExpectancy());

}

每次循环成功两次,第三次迭代给我一个NullPointerException。插入System.out.writeln次调用以进行调试。从writeln调用,我可以看到,在调用方法之前,我传递给writeExternal方法的对象不是空的。在第三次迭代中,我收到以下错误:

Exception in thread "main" java.lang.NullPointerException
    at edu.wmich.cs3310.jwhite_cotw.DataTable.writeExternal(DataTable.java:255)
    at edu.wmich.cs3310.jwhite_cotw.DataTable.put(DataTable.java:159)
    at edu.wmich.cs3310.jwhite_cotw.Setup.main(Setup.java:62)

我无法弄清楚null的来源。如果对象在调用方法之前不是null,那么该如何为null?有没有人有任何想法?我应该提到字段“this.file”是用“rw”打开的RandomAccessFile

DataTable.java:255是

this.file.writeUTF(data.getCountryCode());

DataTable.java:159是

writeExternal(this.current);

和Setup.java:62是

table.put(record);

任何建议(即使只是正确方向上的一点)都会受到最高的赞赏。

2 个答案:

答案 0 :(得分:1)

错误是writeExternal的参数为null时的错误。所以声明是有问题的

writeExternal(this.current);

如果您将其更改为

writeExternal(country);

它可以帮助您避免错误,但可能您应该重新设计代码以处理nullpointer异常,或者至少使用throws子句声明它。

答案 1 :(得分:-1)

因为我是通灵者,我可以说出问题是什么......

countryCode字段的类型为Integer,但参数类型exists()int。这意味着当将countryCode传递给方法时,Integer会自动取消装箱到int,但如果countryCode为null,则此操作会导致NPE。

将参数类型更改为Integer,并确保方法处理为null。

免责声明:我的字段和方法名称可能不对,但我非常清楚一般原因。

相关问题