Why is NPE not reported on correct line

Viewed 228

Running the following:

public class NPESample {

  String value;

  public static void main(String[] args) {
    NPESample npeSample = null;
    "foo"
        .replaceAll(
            "f",
            npeSample.value);
  }
}

Will give:

Exception in thread "main" java.lang.NullPointerException
    at NPESample.main(NPESample.java:9)

Reported line (7) is the line "foo" and not the actual line where NPE happens (10) npeSample.value.

Why is this? I was caught by surprise when debugging code and thrown off by the "wrong" reported line number in the code.

To reproduce run this:

cat > ./NPESample.java <<DELIM
public class NPESample {

  String value;

  public static void main(String[] args) {
    NPESample npeSample = null;
    "foo"
        .replaceAll(
            "f",
            npeSample.value);
  }
}
DELIM

javac NPESample.java
java NPESample

output is:

Exception in thread "main" java.lang.NullPointerException
    at NPESample.main(NPESample.java:7)
javac -version
javac 13.0.1
java -version
openjdk version "13.0.1" 2019-10-15
OpenJDK Runtime Environment (build 13.0.1+9)
OpenJDK 64-Bit Server VM (build 13.0.1+9, mixed mode, sharing)
1 Answers

This does not look like a bug, to me. Specifically, it seems that the mapping is freely allowed not be one-one, as the SPEC says:

That is, LineNumberTable attributes may together represent a given line of a source file, and need not be one-to-one with source lines.

Even JDK-15 reports the wrong line:

Cannot read field "value" because "npeSample" is null

on line 9.

Related