Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should I throw when building cache fail?

Tags:

java

exception

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.

like image 337
Genzer Avatar asked May 18 '11 08:05

Genzer


2 Answers

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.

like image 138
skaffman Avatar answered Sep 30 '22 14:09

skaffman


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.
like image 36
Nicolas Bousquet Avatar answered Sep 30 '22 12:09

Nicolas Bousquet