42. Checking null references and throwing the specified exception

Of course, one solution entails relying directly on the == operator as follows:

if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}

This problem cannot be solved via the methods of java.util.Objects since there is no requireNonNullElseThrow() method. Throwing IllegalArgumentException or another specified exception may require a set of methods, as shown in following screenshot:

Let's focus on the requireNonNullElseThrowIAE() methods. These two methods throw IllegalArgumentException with a custom message specified as String or as Supplier (to avoid creation until null is evaluated to true):

public static <T> T requireNonNullElseThrowIAE(
T obj, String message) {

if (obj == null) {
throw new IllegalArgumentException(message);
}

return obj;
}

public static <T> T requireNonNullElseThrowIAE(T obj,
Supplier<String> messageSupplier) {

if (obj == null) {
throw new IllegalArgumentException(messageSupplier == null
? null : messageSupplier.get());
}

return obj;
}

So, throwing IllegalArgumentException can be done via these two methods. But they are not enough. For example, the code may need to throw IllegalStateException, UnsupportedOperationException, and so on. For such cases, the following methods are preferable:

public static <T, X extends Throwable> T requireNonNullElseThrow(
T obj, X exception) throws X {

if (obj == null) {
throw exception;
}

return obj;
}

public static <T, X extends Throwable> T requireNotNullElseThrow(
T obj, Supplier<<? extends X> exceptionSupplier) throws X {

if (obj != null) {
return obj;
} else {
throw exceptionSupplier.get();
}
}

Consider adding these methods to a helper class named MyObjects. Call these methods as shown in the following example:

public Car(String name, Color color) {

this.name = MyObjects.requireNonNullElseThrow(name,
new UnsupportedOperationException("Name cannot be set as null"));
this.color = MyObjects.requireNotNullElseThrow(color, () ->
new UnsupportedOperationException("Color cannot be set as null"));
}

Furthermore, we can follow these examples to enrich MyObjects with other kinds of exceptions as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset