The code below does not compile because the initializer block can throw an exception. This is explicitly allowed in the language spec (second edition), sec. 8.6, page 188:
An instance initializer of a named class may not throw a checked
exception unless that exception or one of its superclasses is
explicitly declared in the throws clause of each constructor of its
class and the class has a least one explicitly declared constructor.
The code meets these criteria, but the compiler does not let it pass.
import java.io.*;
class TestInitExcept {
static boolean stuff;
{
if (stuff)
throw new IOException("Junk");
}
TestInitExcept() throws IOException {
}
public static void main(String[] args) {
try {
TestInitExcept t = new TestInitExcept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
An instance initializer of a named class may not throw a checked
exception unless that exception or one of its superclasses is
explicitly declared in the throws clause of each constructor of its
class and the class has a least one explicitly declared constructor.
The code meets these criteria, but the compiler does not let it pass.
import java.io.*;
class TestInitExcept {
static boolean stuff;
{
if (stuff)
throw new IOException("Junk");
}
TestInitExcept() throws IOException {
}
public static void main(String[] args) {
try {
TestInitExcept t = new TestInitExcept();
} catch (IOException e) {
e.printStackTrace();
}
}
}