codingenious
codingenious

Reputation: 8653

use try catch in static initialization block

I am not throwing any exception out of static block.

static 
{
    try
    {
        int number = Integer.parseInt("2a");
    }
    catch (NumberFormatException e)
    {
        //log
    }
}

Why using try and catch is considered wrong in this case?

Upvotes: 6

Views: 12913

Answers (2)

rachana
rachana

Reputation: 3414

You cannot throw Checked Exceptions in Static block

In methods, an exception can be handled by either passing through the Exception or handling it. But in a static block code, you cannot handle exceptions this way.

Generally a clean way to handle it is using a try-catch block but here since we dont have this option lets look at the available three options.

First: After logging the exception throw a RuntimeException which will end the current thread (unless caught by code instantiating / calling a static method on the class for the first time).

Second is calling System.exit(1) but this is not desirable in a managed environment like a servlet. This option is only for java applications and only if the static initializer block performs some critical (without which the program cannot be run successfully) function like loading the database driver.

Third and final option is to set a flag indicating failure. Later the constructors can check the flag and throw exceptions or retry in rare cases.

Finally, if the operation is not important to the functioning of the program then maybe a simple log entry is all that is required.

for more detail about static blocks go through this link.

Upvotes: 5

bstar55
bstar55

Reputation: 3624

The static block must not throw checked exceptions but still allows unchecked/runtime-exceptions to be thrown.

That said, there's nothing inherently wrong about using a try catch in a static block. As stated above, this is actually a requirement if the code throws a checked exception.

Upvotes: 6

Related Questions