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

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

    In your case: neither. Check for null and throw more meaningful exception, not NPE.

    In general - if NPE should not occur, don't test for it explicitly, Java will do it for you. Less tests to write, less code to read, less complexity to analyze.

    However if null is expected test it as soon as possible and interpret accordingly. Otherwise NullPointerException will occur somewhere later in different line/method, making it harder to debug the real problem.

提交回复
热议问题