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.
IllegalStateException
would be a reasonable fallback position, but you should never, ever use ExceptionInInitializerError
(or anything ending in Error
) - that's low-level classloader stuff, don't mess with that.
Clearly I can create my own ErrorOnBuildingCache and throw it but I wonder if any exception in Java library suits this circumstance.
This is exactly what you should do. Do not try to use an existing exception, but instead make one of your own. So you know when it is throwed that it is related to your cache and not a static field instanciation error or something.
On a side note, you shouldn't catch exception excepted in very specific cases. Catching exception will catch everything like null pointer exceptions, divide by zero, IO errors, security exception.
What I would do is:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With