Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to throw exceptions for constructor

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

Hey above I have the constructor for one of my classes. My question is should I add null pointer exceptions to the constructor or would this be unnecessary? Honestly, I just don't understand when I should 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;
}
like image 536
Wang-Zhao-Liu Q Avatar asked Sep 20 '26 23:09

Wang-Zhao-Liu Q


1 Answers

Well... It is a matter of taste.

If the preconconditions for the class is that rootRegion has to be provided, it makes sense to protect the class implementation from the need to make null checks all over the place.

So to answer the question "When should I throw exception in a constructor" : I would do it in all cases where the parameters, from the consumer, brings your implementation in a invalid state, delegate the problem (ie. throw the exception).

If you try to take the role as consumer for a while, and you choose not to make the null-checks he will have code like:

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

If he reach the 2nd line, and the implementation here throws a NullPointerException it will not be clear for him that it is due to the parameters he provided.

like image 69
The eternal newbie Avatar answered Sep 23 '26 11:09

The eternal newbie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!