Problem
I have a class with two constructors. One of them (A) throws a checked exception, and the other one (B) calls the first one.
// Constructor A
public ArrayValue(DataType rules, Value... content) throws NonExpressionException {
super(rules.type);
...
}
// Constructor B
public ArrayValue(Value... content) {
this(TypeConstants.VAR_ARR, content);
}
The problem is, that this checked exception will never get thrown when constructor B is invoked, so I thought of "catching" it instead of adding a "throws" to this constructor.
Question
What can I do to get rid of the "throws"? My conditions are:
- The first constructor has to throw this exception.
- It has to be checked.
- I dont want to copy the whole code from constructor A into B.
- I'm looking for a more elegant solution than just changing the constructor B to a static method.
I have tried
// Constructor B
public ArrayValue(Value... content) {
try {
this(TypeConstants.VAR_ARR, content));
catch (NonExpressionException e) {
throw new AssertionError("This shouldn't get thrown", e);
}
}
(But that doesn't work, because this() has to be the first statement in a constructor.)
For this level of flexibility, a helper factory method would come in handy:
However, at this point, it might be worth considering using static factory methods instead (as suggested in the comments). In Effective Java, 3rd Edition, the first item is "Consider static factory methods instead of constructors". Bloch lists four advantages of using static factory methods instead of constructors. Interestingly, dealing with pesky checked exceptions is not one of them, but it could be.