Effective Java (Second Edition), Item 4, discusses using private constructors to enforce noninstantiability. Here's the code sample from the book:
public final class UtilityClass {
private UtilityClass() {
throw new AssertionError();
}
}
However, AssertionError
doesn't seem like the right thing to throw. Nothing is being "asserted", which is how the API defines the use of AssertionError.
Is there a different Throwable
that's typically in this situation? Does one usually just throw a general Exception
with a message? Or is it common to write a custom Exception
for this?
It's pretty trivial, but more than anything I guess I'm just curious about it from a style and standards perspective.
There is an assertion: "I'm asserting that this constructor will never be called". So, indeed, AssertionError
is correct here.