java - 为什么没有在正确的行上报告 NPE

标签 java nullpointerexception stack-trace

运行以下内容:

public class NPESample {

  String value;

  public static void main(String[] args) {
    NPESample npeSample = null;
    "foo"
        .replaceAll(
            "f",
            npeSample.value);
  }
}
会给:
Exception in thread "main" java.lang.NullPointerException
    at NPESample.main(NPESample.java:9)
报告的第 (7) 行是 "foo"而不是发生 NPE 的实际线路 (10) npeSample.value .
为什么是这样?我在调试代码时感到惊讶,并被代码中报告的“错误”行号所抛弃。
要重现运行这个:
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
输出是:
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)

最佳答案

对我来说,这看起来不像是一个错误。具体来说,好像是自由映射不是一对一的,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.


JDK-15报告错误的行:

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


在线9 .

关于java - 为什么没有在正确的行上报告 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64022079/

相关文章:

java - 模余数与java和php不同

java - 使用 JavaParser 计算类中的方法声明 + 方法调用

java - 如何从 Java 中的对象 vector 获取特定类型的对象

java - 严重: Exception occurred during processing request: null java. lang.NullPointerException

c# - 在异步/等待应用程序中获取所有堆栈跟踪

java - 从 cmd 刷新 Eclipse gradle

java - 空变量不会使方法引用无效

java - 在编写 if-else 编译器时会报错,但为了简写它不会报错,为什么?

c# - 是否可以从Exception.StackTrace中提取一些结构化信息?

java - 堆栈中的push(int[][])复制相同的值Java