7

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

codingenious
  • 8,385
  • 12
  • 60
  • 90

2 Answers2

11

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 7
    I don't get how you can read a question, write an answer and find the important quote from the specification and do all that in the same minute the question was posted... +1 – noone Oct 20 '13 at 14:41
  • @noone Jon has had more practice than most, never the less... ;) – Peter Lawrey Oct 20 '13 at 14:42
  • 2
    @noone: Well the *original* answer was pretty quick - but I expanded it afterwards, and edits within the first five minutes aren't shown... – Jon Skeet Oct 20 '13 at 14:43
  • @noone - this is called experience and it does count. Thanks Jon :) – codingenious Oct 20 '13 at 14:48
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130