public class Rectangle {
int width, height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(Rectangle source) {
this(source.width, source.height);
}
}
Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).
Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException
if it is? Because the other constructor call has to be the first statement in my constructor.
You could introduce a private static method that returns the relevant value with a null
check to throw the IllegalArgumentException
(in this case the width as it's the first parameter on the same object).
For example:
public class Rectangle {
private int width, height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(Rectangle rectangle) {
this(getWidth(rectangle), rectangle.height);
}
private static int getWidth(Rectangle rectangle) {
if (rectangle == null) {
throw new IllegalArgumentException("null value");
}
return rectangle.width;
}
}
Reflecting on the comment to the question above, why not NullPointerException
?
This question: IllegalArgumentException or NullPointerException for a null parameter? has some good discussion points. But I'm inclined to agree with the sentiments of "Effective Java" that NullPointerException
should be preferred as cited in this answer to that very question.
"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 parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With