What exception should I throw when the cache fails?

I have a class that contains a cache (Set), and the cache is built on instantiation. I am confused which exception / error I should use if the building cache fails (it is not possible to connect to the database or to some).

class Provider { public Provider() { buildCache(); } private void buildCache() { try { this.cache = getDataFromDb(); } catch (Exception ex) { throw new ??? } } } 

The only exception comes to my mind: ExceptionInInitializerError , but javadoc says it is initialized with static members.

Should I throw an IllegalStateException because the cache is not built, so this class is useless?

It is clear that I can create my own ErrorOnBuildingCache and throw it away, but I am wondering if any exception in the Java library is suitable for this circumstance.

+6
source share
2 answers

If you doubt which exception should be thrown, then there will be users of your code. Therefore, define your own exception type (for example, FailedToInitializeCacheException ) and throw it. There is no such ambiguity.

IllegalStateException would be a reasonable fallback position, but you should never use an ExceptionInInitializerError (or anything ending with Error ) - this low-level class loader class, don't go into it with this.

+9
source

It is clear that I can create my own ErrorOnBuildingCache and throw it, but I wonder if any exception in the Java library is suitable for this circumstance.

This is exactly what you should do. Do not try to use an existing exception, but instead make your own. That way, you know, when it is thrown, that it is associated with your cache, and not with a static field initialization error or something like that.

On the other hand, you should not exclude an exception, excepting only in special cases. The exception exception will catch everything as null pointer exceptions, divide by zero, I / O errors, security exception.

What would I do:

  • Include reason for repeated exclusion for better investigation.
  • Catch exceptions that may occur due to problems with the IO / Network, but associate them with the correct error message. In this case, these are DB exceptions.
  • Do not catch an exception for programming errors (for example, null pointers), let them pop up so that you directly know the cause of the real error.
+1
source

Source: https://habr.com/ru/post/888392/


All Articles