• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance Initializer Block

 
Steven Wong
Ranch Hand
Posts: 295
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
For instance initializer block, all constructors must declare the uncaught checked exceptions, if any.
Can someone explain these more clearly, preferable with some code snipplets?
I understand that for static initializer blocks,we cannot pass on the checked exceptions. Instead we must catch and handle them.
Clement
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Clement, look this code and the compiler error:

There is an error about a checked exception that is not declared to be thrown in every constructor. However, uncomment the declaration in the second constructor and you won't see any error.
To understand this, remember that the code of the instance initializers is gathered and placed inmediately after the implicit/explicit call to the super cosntructor in every constructor that doesn't begin with a call to this(...). This is the mechanism by wich instance fields are initialized to the expressions given at the point of the declaration, before being intialized to the expressions in a constructor. "javap -c MyClass" can be used to verify it.
Thus, because the code in the instance initializer is placed inside the constructor, they must declare the checked excetions thrown by the instance initializers.
[ May 03, 2002: Message edited by: Jose Botella ]
 
Steven Wong
Ranch Hand
Posts: 295
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the prompt reply.
However does this rule apply for checked exceptions only or for unchecked exceptions as well?
Cos the code below does not compile.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have no a compiler at the moment. Are you sure the code doesn't compile? Because in my example the only error is about the checked exception.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look closer at the error you get from the compiler. The reason this doesn't compile isn't because of the exception, it's because you don't have braces to define a body for your constructor.
This line is the culprit:

Corey
 
Steven Wong
Ranch Hand
Posts: 295
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, I'm sorry for the silly mistake.
Thanks Corey.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic