开发者

Which exception should I throw when building cache fail?

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();
   }

   privat开发者_如何转开发e 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:

  • Include the cause when rethrowing the exception to allow better investigation
  • Catch exceptions that could occurs due to IO/Network problems but associate them with the right error message. In you case this is DB exceptions.
  • Do not catch exception that are due to programming bugs (like null pointers), let them popup so you directly know the real error cause.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜