Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can initializer block throw exception?

Tags:

java

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 :)

like image 848
codingenious Avatar asked Oct 20 '13 14:10

codingenious


2 Answers

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.

like image 97
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet


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

Yes there is but it is very bad idea. You can do this

class ReadFromFile {
    BufferedReader br;

    {
        try {
            br = new BufferedReader(new FileReader(new File("file.txt")));
        } catch(IOException ioe) {
            // there is a number of ways to blindly throw a checked exception.
            Thread.currentThread().stop(ioe); // don't try this at home.
        }
    }
}

This all compiles and works, but it is needlessly confusing.

like image 36
Peter Lawrey Avatar answered Oct 06 '22 01:10

Peter Lawrey