Illegalargumentexception or NullPointerException for a null parameter?
Your best friends here are IllegalArgumentException
when null or unsuitable values breach the contract, and NullPointerException
only if the contract specifically prohibits nulls, like in these cases:
The essential nugget here: Use NullPointerException
strictly for null-related contract violations, and employ IllegalArgumentException
for the broader spectrum of invalid inputs.
The fail-fast principle
If you deny the existence of pests at the beginning of your fruit cultivation, you don't have to deal with the infestation later. Yep, that's the fail-fast principle. Pinpointing these pests are our two exceptions:
-
IllegalArgumentException
suggests that a bad apple (not restricted to nulls) has slipped into your batch. -
NullPointerException
emphasizes the issue when you try to inspect an apple (which should be present), but it is absent.
Strong advice: Craft clear and concise exception messages; it’ll help to diagnose the issue faster.
Context is key
Is the mailbox full or did the letter never arrive? The exception you throw should mirror the exact issue you encounter.
If null is an anticipated shortcoming matching your API's blueprint, throw a NullPointerException
. If the value (including null) does not fit the contract, chuck an IllegalArgumentException
. Keep the readability and maintainability of your code in mind while selecting your throwable.
Sing in harmony
Achieve consistency in managing null parameters across your code by opting for IllegalArgumentException
— it's common to use it for validating a range of data types, not just nulls.
Including the parameter name in exception messages aids debugging efforts. Stick to your API's design, even if it suggests throwing a NullPointerException
occasionally.
Performance insights
While performance rarely influences exception choice, it's noteworthy that JVM-internal NullPointerExceptions
thrown from Java 7 onward can be optimized for JIT compilation, reducing potential degradation. However, this should not be a determining factor over clarity and API design.
Respected guidelines
Books akin to Effective Java offer valuable conversations about these exceptions. These texts underline the necessity of a crystal-clear API design and using exceptions to indicate contract shortcomings.
Was this article helpful?