Why does requireNotNull throw an IllegalArgumentException?


The requireNotNull function throws an IllegalArgumentException instead of the more precise NullPointerException:

> requireNotNull(null)
java.lang.IllegalArgumentException: Required value was null.

Josh Bloch suggests in “Effective Java” to use the most precise Exception available, what is a NullPointerException in this case (and exactly this case in the book).

Why does Kotlin treat it differently? Shouldn’t it be changed?


I think the reasoning is this. A Null pointer exception gets thrown when you try to access a field of a null object like null.someValue. The require functions in Kotlin are designed to check that the arguments passed to a function are valid. Therefor an argument exception is the right exception. The argument passed is invalid because it is null. Kotlin never tries to access the value behind the null reference and that is why this does not throw a NullPointerException.
At least that’s what I would think the reason is. Another reason could be the fact, that NullPointerExceptions in Kotlin normally mean that there is a serious error. Kotlin only uses them if you use null!! or if you actually try to dereference a null reference (which can happen in constructors or in case of serialization I think). Basically a NullPointer in Kotlin means that either you have done something you shouldn’t with (!!) or some java code you called failed.

PS: If you are using requireNotNull to do some asserting or checking the state of an object you should use assert/check instead. As I said above require is used for checking the validity of arguments passed to a function, assert is assert and check is used to test the validity of the current state of an object (e.g this function can only be called after some state has been calculated).