Name: mc57594 Date: 05/23/97
An instance initializer is allowed to throw a checked
exception if that exception type is declared in the throws list of every
constructor. Thus the following code is legal:
class B
{
class C
{
C () throws Throwable
{
}
{
int j = 5;
if (j == 6)
throw new Throwable(); // thrown by constructor
}
}
}
However javac rejects this.
Also note that initializers in anonymous classes may throw ANY checked
exception type.
======================================================================
Copied from 4030341, closed as duplicate, by william.maddox@Eng 1998-01-27:
The inner classes white paper says that a checked exception may be raised
in an instance initializer if all constructors declare a throw for it,
and that the automatically generated constructor for an anonymous class
automatically throws the correct exceptions, so that any exception can be
raised in the body of an anonymous class.
The compiler produces several errors if this is attempted. Here is an example:
// this is JCK 1.1 test innr088
class InitExceptionBug0 {
void f() throws InstantiationException {
new Object() {
{
throw new InstantiationException("test");
}
};
}
}
The compiler output looks like this:
InitExceptionBug0.java:4: Statement not reached.
new Object() {
^
InitExceptionBug0.java:4: Constructor invocation must be the first thing in a method.
new Object() {
^
InitExceptionBug0.java:6: Exception java.lang.InstantiationException can't be thrown in initializer.
throw new InstantiationException("test");
^
3 errors
- duplicates
-
JDK-4030341 Checked exceptions in anonymous instance initializers not processed correctly.
-
- Closed
-
-
JDK-4052099 Not all exception types work with initializers
-
- Closed
-
-
JDK-4210130 An instance initializer in an anonymous class can't throw checked exceptions
-
- Closed
-