3

I have been very clear that instance initializer cannot throw exception because it is part of object initialization and developer has no control over this process. This post has the same idea.

However, I have read an article by Bill Venners about the object initialization in java, and there is one paragraph quoted as below:

The code inside an instance initializer may not return. Except in the case of anonymous inner classes, an instance initializer may throw checked exceptions only if the checked exceptions are explicitly declared in the throws clause of every constructor in the class. Instance initializers in anonymous inner classes, on the other hand, can throw any exception. Please click here for original post.

It seems to say that an instance initializer can throw exception. Could anyone here explain this to me or correct me if my understanding is not correct.

Community
  • 1
  • 1
Hong
  • 55
  • 5

1 Answers1

2

Instance initializers can throw checked exceptions, but if they do, the class constructor has to declare them. For example, this code is legal:

import java.io.*;

public class MyClass {

    PrintStream stream;

    {
        stream = new PrintStream("/tmp/file.txt");
    }

    public MyClass() throws FileNotFoundException {
    }

}

If, however, the throws clause was omitted from the constructor, or if another constructor was added that didn't also have the clause this would not compile, because the PrintStream constructor throws FileNotFoundException.

Taymon
  • 24,950
  • 9
  • 62
  • 84
  • 1
    Going along with your answer, instance initializers can throw unchecked exceptions without the class constructor restriction. – emory Dec 02 '11 at 07:03