Should I throw a NullPointerException explicitly or let Java do it for me?

前端 未结 6 2143
一整个雨季
一整个雨季 2021-02-19 13:23

As the title says, I am wondering what the best practice is regarding the throwing of NullPointerExceptions. Specifically, if I have an external library function that can return

6条回答
  •  既然无缘
    2021-02-19 13:34

    I dont like having null be a valid return value, even in "exceptional circumstances". So I take yet another approach.

    In your case I'd annotate the method createSynthesizer(...) with @NotNull (@NotNull is an amazing annotation). Instead of an NPE, I'd get an IllegalStateException as soon as createSynthesizer(...) would want to return null.

    You'd get a:

    java.lang.IllegalStateException: @NotNull method .../.../createSynthetiser(...) must not return null
    

    There are several benefits to this approach:

    • both NullPointerException and IllegalStateException extends RuntimeException so you're not fundamentally changing your program

    • the exception shall be thrown immediately where the error happens (not later on, once you either check/throw yourself or once you try to dereference null)

    • you don't need to bother writing the if ... == null / throw part anymore.

    As a, gigantic, added benefit some IDE (like IntelliJ IDEA) will warn you in real-time about probable @NotNull violations.

提交回复
热议问题