Hi,
I'm studying the following term of Java Spec3 8.2 Class instance
initializer.
=== quote ===
"It is compile-time error if an instance initializer of a named class
can throw a checked exception unless that exception or one of its
supertypes is explicitly declared in the throws clause of each
constructor of its class and the class has at least one explicitly
declared constructor. "
===
I wrote a small piece of code to test it.
=== code begin ==
package test.java.langspec.cls;
import java.io.*;
public class TestInstanceInitializer {
{// instance initializer
throw new IOException("aaa");
}
TestInstanceInitializer() throws Exception {
}
}
=== code end ====
under Linux, Eclipse3.2,Jdk1.5_11, it report compile error
"Initializer does not complete normally".
I tried to wrap the throw statement into a member method, like this
=== code begin ==
package test.java.langspec.cls;
import java.io.*;
public class TestInstanceInitializer {
{// instance initializer
throwExcpt();
}
TestInstanceInitializer() throws Exception {
}
void throwExcpt() throws IOException {
throw new IOException("aaa");
}
}
=== code end ====
This time, it's OK,
but, my problem is why the first code pattern, it's doesn't work?
is any mystery under it ? ^_^
thanks in advance.
-skyofdreams
SadRed - 30 Mar 2007 05:45 GMT
> Hi,
>
[quoted text clipped - 56 lines]
> thanks in advance.
> -skyofdreams
Try this:
---------------------------------------
import java.io.*;
public class TestInstanceInitializer {
{
if (1 == 1){
throw new IOException("aaa");
}
}
TestInstanceInitializer() throws Exception {
}
}
---------------------------------------
Method call and if statement are assumed to be 'can throw exception'
state as the spec describes whereas your first instance initialzer is
'always throws exception' state. If it always throws exception, it
can't complete normally.
skyofdreams - 30 Mar 2007 10:29 GMT
> Try this:
> ---------------------------------------
[quoted text clipped - 15 lines]
> 'always throws exception' state. If it always throws exception, it
> can't complete normally.
yes, it works.
Thanks SadRed
so I understand that i need continue to read the Exception chapter of
JavaSpec3. [chuckle]
-Wisdo