Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to notify the programmer of a null argument?
    primarykey
    data
    text
    <p>So, I'm working on designing a class wherein if certain arguments to certain methods are null, either the method (or the object as a whole) won't work.</p> <p>I know that it'll throw a <code>NullPointerException</code> once it receives the null object and attempts to use it, but I want the programmer trying to call the method to understand that the bug is not in my code. I just want to ensure that the resulting exception thrown would be very clear (without the need to look into my source).</p> <p>I've seen a few examples of what I described, where they throw an <code>IllegalArgumentException</code> when the parameter is null.</p> <p>Here's the difference, imagine that someObject will somehow be vital to the method:</p> <pre><code>public void doSomething(SomeClass someObject) { if (someObject == null) throw new IllegalArgumentException("someObject is null"); ... } </code></pre> <p>This way, the programmer understands that he or she has broken the contract implied by the javadoc (whether or not it is explicitly stated).</p> <p>Is that good practice, or even a reasonable thing to do?</p> <hr /> <h3>Quick Edit/Side-bar:</h3> <p>What would be best to say in the exception message?</p> <p>Is it better to state what "went wrong":</p> <blockquote> <p>someObject is null</p> </blockquote> <p>Or is it better to state that something "went wrong" and generally imply the cause (and ultimately the solution):</p> <blockquote> <p>someObject cannot be null</p> </blockquote> <p>Or is there a better alternative?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload