I have a class that contains a cache (Set), and the cache is built on instantiation. I’m confused which exception/error should I throw if building cache fail (cannot connect to database or some).
class Provider {
public Provider() {
buildCache();
}
private void buildCache() {
try {
this.cache = getDataFromDb();
} catch (Exception ex) {
throw new ???
}
}
}
One exception comes in my mind is ExceptionInInitializerError, but javadoc says it is thrown on initialize static members.
Should I throw an IllegalStateException cause the cache isn’t built so this class is useless?
Clearly I can create my own ErrorOnBuildingCache and throw it but I wonder if any exception in Java library suits this circumstance.
If you’re in doubt as to which exception should be thrown, then so will users of your code. So define your own exception type (e.g.
FailedToInitializeCacheException) and throw that. No ambiguity that way.IllegalStateExceptionwould be a reasonable fallback position, but you should never, ever useExceptionInInitializerError(or anything ending inError) – that’s low-level classloader stuff, don’t mess with that.