Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instance Initializer Block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instance Initializer Block" Watch "Instance Initializer Block" New topic
Author

Instance Initializer Block

Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
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


best regards,<br />Steven<br />SCJP, SCEA
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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 ]

SCJP2. Please Indent your code using UBB Code
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
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

Joined: Jul 03, 2001
Posts: 2120
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

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
Oops, I'm sorry for the silly mistake.
Thanks Corey.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Instance Initializer Block
 
Similar Threads
Initialization Blocks
exception handling in instance initializer
question about code in { }
Initialzer's
exception in static initialiser