Can initializer block throw exception?

I am using BufferedReader in a class to read from a file. I am trying to initialize this in initializer block.

class ReadFromFile
{
    BufferedReader br;

    {
        br = new BufferedReader(new FileReader(new File("file.txt")));
    }
}

line in initializer block throws FileNotFoundException exception. So, compiler gives error. I dont want to surround it with try-catch block. I solved the problem by using constructor instead of initializer block like :

class ReadFromFile
{
    BufferedReader br;

    public ReadFromFile() throws FileNotFoundException   
    {
        br = new BufferedReader(new FileReader(new File("file.txt")));
    }
}

But still want to know if there is any way to throw exception out of initializer block without getting compilation error. Thanks :)

Jon Skeet
people
quotationmark

An initializer block can only throw unchecked exceptions, or checked exceptions which are declared to be thrown by all constructors. (This includes exceptions which are subclasses of those which are declared.)

You can't throw a checked exception from an initializer in a class with no declared constructors, as you'll effectively be provided with a parameterless constructor which doesn't declare that it throws anything.

From section 11.2.3 of the JLS:

It is a compile-time error if an instance variable initializer or instance initializer of a named class can throw a checked exception class unless that exception class or one of its superclasses is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor.

people

See more on this question at Stackoverflow