Java – when to throw an exception for a constructor

public Neocortex(Region rootRegion,ConnectionInterface functor) {
public Neocortex(Region rootRegion,ConnectionInterface functor) {
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}

Hey, I have a class constructor above My question is should I add a null pointer exception to the constructor or is it unnecessary? To be honest, I just don't know when to add exceptions to my code But in this case, which constructor should I use?

public Neocortex(Region rootRegion,ConnectionInterface functor) {
    if (rootRegion == null) {
    throw new NullPointerException("rootRegion cannot be null");
} else if (functor == null) {
        throw new NullPointerException("functor cannot be null");
    }
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}

Solution

Well... It's a matter of taste

If the precondition of the class is that rootregion must be provided, it makes sense to protect the class implementation without null checking in the whole place

Therefore, answer the question "when should I throw an exception in the constructor": I will do this in all cases, where the parameters from the consumer invalidate your implementation, delegate the question (that is, throw an exception)

If you try to use a role as a consumer for a period of time and you choose not to perform a null check, he will have the following code:

Neocortex n = new Neocortex(null,null);
n.doSomeething();

If he reaches the second line and the implementation here throws a NullPointerException, he will not know that it is due to the parameters he provides

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>