The code below will not compile. One line needs a single change to make it compile. What is the change required? (Hint: This is not a simple syntax error like a missing semicolon. Don't try to play compiler. There is a more fundamental problem.)
I believe the initialization of the instance variables & initializers are all 'lump' together with the code of the constructor to form the <init> method. So if any of those throws an exception, it must be declared in the constructor. Is that correct? [ August 13, 2003: Message edited by: Alton Hernandez ]
Unni Kainila
Ranch Hand
Joined: Jul 26, 2003
Posts: 45
posted
0
I guessed the same. Good excercise for my GC lesson! [ August 13, 2003: Message edited by: Unni Kainila ]
rani bedi
Ranch Hand
Joined: Feb 06, 2001
Posts: 358
posted
0
c variable need to be initialized in the constructor which throws Exception
Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Alton has the correct answer. The rule is that if an instance variable initializer can throw an exception then every constructor must throw that exception. Good job! Now go out an but a copy of JavaRules from amazon for less than $5!!! [ August 14, 2003: Message edited by: Thomas Paul ]
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
hi Thomas i knew the answer Alton wrote BUT i tried to confirm it using a program. guess what? it didnt work for me so i didnt post my answer, here is what i wrote and got, Program: ------- import java.util.*; public class ABC { Calendar c = setCalendar(); public ABC() throws Exception {} Calendar setCalendar() throws Exception{ Calendar rightNow = Calendar.getInstance(); if (rightNow.get(Calendar.MONTH) == Calendar.AUGUST) throw new Exception("Don't run this in August"); return rightNow; } }
Result of javac: ---------------- ABC.java:5: Exception java.lang.Exception can't be thrown in initializer. Calendar c = setCalendar(); ^ 1 error
then i realized why it would not work and wrote the code Prameet came up with later on. that code worked but u specified in the question that only one line needed to change to make the code compile successully and so i thought my answer is invalid not that i want the book but just to make sure we know the correct answer. regards maulin
I bought my copy from one of these guys and it was almost perfect condition. The only thing that was less than perfect was a stamp on the back saying that it couldn't be returned to the publisher.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.