Let’s say I have a class that needs to do some initialization work in its constructor. There is no reason to believe that it will fail, but if it does, the instance (and possibly the application; let’s consider these to be two separate cases) will be left in an unusable state with no real hope of recovery within that scope (instance or global).
What is the recommended way to deal with this situation in Java? Rethrowing the exception, wrapped inside a runtime exception, seems like a natural approach, but is there any recommendations or consensus about which exception type to use for such a purpose?
If something in your constructor throws an exception you could either declare it to throw exceptions itself or maybe wrap them with a more general exception (like an own InstantiateXxxxException).
Generally, you have multiple types of
Throwablethat have a different meaning.I’d classify them as follows: