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