Why explicitly throw a NullPointerException rather than letting it happen naturally?

后端 未结 9 1463
无人共我
无人共我 2020-12-12 13:40

When reading JDK source code, I find it common that the author will check the parameters if they are null and then throw new NullPointerException() manually. Why do they do

9条回答
  •  悲&欢浪女
    2020-12-12 13:52

    In addition to the reasons listed by @shmosel's excellent answer ...

    Performance: There may be / have been performance benefits (on some JVMs) to throwing the NPE explicitly rather than letting the JVM do it.

    It depends on the strategy that the Java interpreter and JIT compiler take to detecting the dereferencing of null pointers. One strategy is to not test for null, but instead trap the SIGSEGV that happens when an instruction tries to access address 0. This is the fastest approach in the case where the reference is always valid, but it is expensive in the NPE case.

    An explicit test for null in the code would avoid the SIGSEGV performance hit in a scenario where NPEs were frequent.

    (I doubt that this would be a worthwhile micro-optimization in a modern JVM, but it could have been in the past.)


    Compatibility: The likely reason that there is no message in the exception is for compatibility with NPEs that are thrown by the JVM itself. In a compliant Java implementation, an NPE thrown by the JVM has a null message. (Android Java is different.)

提交回复
热议问题