Java - Checked Exceptions and Initializers

Static initializer

You cannot throw a checked exception from a static initializer.

If a piece of code in a static initializer throws a checked exception, it must be handled using a try-catch block inside the initializer itself.

The static initializer is called only once for a class, and there is no specific point in code to catch it.

A static initializer must handle all possible checked exceptions that it may throw.

public class Test {
   static {
      // Must use try-catch blocks to handle all checked exceptions
   }
}

Instance initializers

An instance initializer is called as part of a constructor call for the class.

It may throw checked exceptions.

All those checked exceptions must be included in the throws clause of all constructors for that class.

The compiler can make sure all checked exceptions are taken care of by programmers when any of the constructors are called.

The following code throws a checked exception of a MyException type in instance initializer.

The compiler will force you to add a throws clause with MyException to all constructors of Test.

public class Test {
        // Instance initializer
        {
                // Throws a checked exception of type MyException
        }

        // All constructors must specify that they throw MyException
        // because the instance initializer throws MyException
        public Test() throws MyException {
        }
        public Test(int x) throws MyException {
        }
}

You must handle the MyException when you create an object of the Test class using any of its constructors as

Test t = null;
try {
        t = new Test();
}
catch (MyException e) {
        // Handle exception here
}

Quiz