Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NPE not reported on correct line

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)
like image 225
Raipe Avatar asked Sep 23 '20 06:09

Raipe


People also ask

How do I fix NullPointerException?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Why am I getting a NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

Is NullPointerException checked or unchecked?

Answer: NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.

Why do we get NullPointerException in selenium?

NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.


Video Answer


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.

like image 84
Eugene Avatar answered Oct 25 '22 16:10

Eugene