Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (2.6k points)

I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?

1 Answer

0 votes
by (46k points)

It appears like an IllegalArgumentException is summoned for if you don't want null to be an allowed value, and the NullPointerException would be executed if you were attempting to use a variable that returns out to be null.

The usually reliable "Effective Java" explains this briefly in Item 42 (first edition), Item 60 (second edition), or Item 72 (third edition) "Favor the use of standard exceptions":

"Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameters for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException."

Related questions

0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
+1 vote
4 answers
0 votes
1 answer

Browse Categories