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)
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.
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.
Answer: NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With