So, I have a class called Puzzle, and two (relevant) constructors for it. One constructor accepts no args, and the other takes an int, but also throws an exception. The basic idea is like this:
public class Puzzle {
// Fields, methods, etc.
public Puzzle() {
this(3);
}
public Puzzle(int n) throws Exception {
if (n < 2) throw new Exception();
// More constructor code
}
}
Of course, this doesn't compile, because the constructor that takes an int throws an exception, and the constructor without args doesn't handle or throw the exception. But, since it is plain to see that the exception never will be thrown (there are no more exceptions thrown in the body of the constructor), this shouldn't matter. I could just use a blank try-catch statement like this:
public Puzzle() {
try {
this(3);
} catch (Exception e) {
// Never happens
}
}
The problem here is that the call to this(3) is no longer the first statement of the constructor, so it won't compile. It seems like I have to mark this constructor with a throws clause even though I know it will never throw an exception. This is really annoying, because calling code will then need to have unnecessary try-catch blocks or they will have to throw the exception too. Is there an elegant way around this that I'm missing? I know I could easily copy and paste some code, but that goes against the grain of all that is holy in OOP. Any ideas?