Java – preconditions library throws illegalargumentexception for notnull check
Do you know that Apache commons validate or guava preconditions is a good alternative. When checking whether the object is empty (except spring asset), it will throw illegalargumentexception instead of NullPointerException?
I know JavaDocs says:
But I just don't like it To me, NPE always means that I just forgot to get a null reference somewhere My eyes are so trained that I can find it browsing the log at the speed of a few pages per second. If I do so, bug alerts will always be enabled in my mind Therefore, it would be very confusing to throw it where I expect the illegalargumentexception
Said I had a bean:
public class Person { private String name; private String phone; //.... }
And service methods:
public void call(Person person) { //assert person.getPhone() != null //.... }
In some cases, a person without a phone may be OK (my grandmother doesn't have any phones) But if you want to call such a person, for me, it will call the calling method with illegalargument Look at the hierarchy – NullPointerException is not even a subclass of illegalargumentexception It basically tells you - try calling getter on a null reference again
In addition, there has been discussion, and I fully support this good answer So my question is – do I need to do ugly things like this:
Validate.isTrue(person.getPhone() != null,"Can't call a person that hasn't got a phone");
Is there my way, or is there a library that only throws illegalargumentexception for notnull check?
Solution
Since the topic of this question has evolved into "correct use of illegalargumentexception and NullPointerException", I would like to point out the forward-looking answers in valid java project 60 (Second Edition):