This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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
Joined: Mar 07, 2002
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.
Joined: Jul 03, 2001
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.
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: