Re: NullPointerException, IllegalArgumentException, or AssertionError
for null constructor argument
Daniel Pitts wrote:
I have a constructor that takes a String argument. I'd like to throw an
exception if the constructor is invoked with a null argument, but I'm
not sure which instruction I should use.
NullPointerException is technically accurate, since it is a null
pointer, but it is also an IllegalArgumentException. I think that
IllegalArgumentException is more specific, so I'll probably go with
that, but wanted opinions.
The third option is AssertionError. I could just use assert arg!=null,
and that could be enough. This is for a personal project, so it doesn't
*really* matter, but at the same time its good practice for me to think
about these sort of things :-)
Thoughts?
Here's an example of the difference between assertion and exception
generation. The assertion is forced to hold by the exception handling. If
the exception-handling algorithm were wrong, the null could perhaps slip
through, and the assert would fail. This should never happen.
The assert is there to alert us if the exception failed to do its job. The
programmer is asserting that the exception clause is sufficient.
public class NoNullHolder <T>
{
private final T held;
public NoNullHolder( T toHold )
{
if ( toHold == null )
{
throw new IllegalArgumentException( new NullPointerException(
"null toHold" ));
}
held = toHold;
assert held != null; // postcondition invariant
}
public final T getHeld()
{
assert held != null; // precondition invariant
return held;
}
}
--
Lew