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
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.