javaexceptionstatic-initializer

Why doesn't Java allow to throw a checked exception from static initialization block?


Why doesn't Java allow to throw a checked exception from a static initialization block? What was the reason behind this design decision?


Solution

  • Because it is not possible to handle these checked exceptions in your source. You do not have any control over the initialization process and static{} blocks cannot be called from your source so that you could surround them with try-catch.

    Because you cannot handle any error indicated by a checked exception, it was decided to disallow throwing of checked exceptions static blocks.

    The static block must not throw checked exceptions but still allows unchecked/runtime-exceptions to be thrown. But according to above reasons you would be unable to handle these either.

    To summarize, this restriction prevents (or at least makes it harder for) the developer from building something which can result in errors from which the application would be unable to recover.