When I try to throw an exception in an instance initialization (not class initialization) block I get the error:
initializer must be able to complete normally
Why is it not allowed although Java does it itself?
The following example creates four classes. The class A fails during instantiation because of an ArithmeticException. This can be and handled with a catch. The same for B which fails with a NullPointerException. But when I try to throw a NullPointerException on my own as in C the program does not compile. And I get the same error when I try to define my own RuntimeException as in D. So:
How can I do the same as Java does itself?
// -*- compile-command: "javac expr.java && java expr"; -*-
class expr
{
class A
{
int y;
{{ y = 0 / 0; }}
}
class B
{
Integer x = null;
int y;
{{ y = x.intValue(); }}
}
class C
{
{{ throw new NullPointerException(); }}
}
class Rex extends RuntimeException {}
class D
{
{{ throw new Rex(); }}
}
void run ()
{
try { A a = new A(); }
catch (Exception e) { System.out.println (e); }
try { B b = new B(); }
catch (Exception e) { System.out.println (e); }
try { C c = new C(); }
catch (Exception e) { System.out.println (e); }
try { D d = new D(); }
catch (Exception e) { System.out.println (e); }
}
public static void main (String argv[])
{
expr e = new expr();
e.run();
}
}
means that there must be a possible code path that doesn’t throw an exception. Your examples unconditionally throw, and are therefore rejected. In the other examples, the static analysis doesn’t go far enough to determine that they also throw in all cases.
For example,
compiles, and when run throws