This week's book giveaway is in the Security forum.
We're giving away four copies of Securing DevOps and have Julien Vehent on-line!
See this thread for details.
Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Instance Initializer  RSS feed

 
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Girish Nagaraj
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Balaji...
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!