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

前端 未结 6 2111
一整个雨季
一整个雨季 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:36

    I'd say that you should never explicitly create a NullPointerException and instead use an exception type that more clearly describes the situation. In your case, I'd say IllegalStateException would fit the situation "wrong setup of the system, and pretty unrecoverable from at runtime". Or you could create your own ComponentMissingException. In cases where a required method parameter is null, IllegalArgumentException is typically used.

提交回复
热议问题