posted 11 years ago
I have studied in a book which says:
Instance initializer blocks in anonymous classes have greater freedom, they can throw any exception.
I wrote code to verify it:
class MyCheckedException extends Exception {}
class C {
C(int i) throws Exception {}
}
class A {
public static void main(String[] args) {
int i = new C(3) {
{
throw new MyCheckedException();
}
int getI() {
return 2;
}
}.getI();
}
}
Why Am I getting compile time error???
Instance initializer blocks in anonymous classes have greater freedom, they can throw any exception.
I wrote code to verify it:
class MyCheckedException extends Exception {}
class C {
C(int i) throws Exception {}
}
class A {
public static void main(String[] args) {
int i = new C(3) {
{
throw new MyCheckedException();
}
int getI() {
return 2;
}
}.getI();
}
}
Why Am I getting compile time error???
posted 11 years ago
This is what the statement means :-)
class Sample {
public void m() throws Exception {
throw new Exception();
}
Sample() {}
public static void main(String args[]) throws Throwable{
final Sample obj = new Sample() {
{
m();
}
};
}
}
There is no need to declare that exception in your class's constructor.
class Sample {
public void m() throws Exception {
throw new Exception();
}
Sample() {}
public static void main(String args[]) throws Throwable{
final Sample obj = new Sample() {
{
m();
}
};
}
}
There is no need to declare that exception in your class's constructor.
Bala<br />SCJP 1.4 98%<br />SCBCD 1.3 -- 88%

Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |