Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about anonymous class

 
josie chen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
according to JLS, instance initializers in anonymous class can throw any exception.
I don't know if my imagination of those code is correct or not. Since all I try cause compile error.
this is my testing code:
class AnonyExcptTest{
public void test() {
new AnonyExcptTest(){
{
// I suppose to add exception here.
throw new Exception();
}
public void mytest() throws Exception{
throw new Exception();
}
};
}
}
Who can help me to figure out?
Thanks a lot!
josie@prome.net
[ April 02, 2003: Message edited by: josie chen ]
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know if this has anything to do with your question but you doing a "new" without assigning the result to anything.
 
josie chen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, maybe my testing code is incorrect. could you give me an example to explain 'instance initializers in anonymous class can throw any exception.'
thank you very much.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So, why does the language allow this? Well, let's say you're writing a class, and need the option to throw an exception during object construction. If the class is anonymous, you can't declara a new constructor for it - the only way you can throw an exception during initialization is in an instance initializer (or field initializer, which is pretty similar). Normally in order to throw a checked exception in an initializer, you'd be required to declare all constructors of your class so that they'd declare the new checked exception. But for an anonymous class, this is impossible - no way to declare constructors at all. This is OK since there's no way for anyone to invoke a constructor of your anonymous class anyway, except by calling the code that declares it, which must either catch the exception or declare it. (Note my main() method declares it throws Exception.) Any other code that calls your code will know about the checked exception, even though no constructor was declared to throw it.
 
josie chen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very appreciate you, Jim.
The explaination is very clear.
I think I shoudn't rely on develper tool too much. Cause the results are different.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic