exception handling - Java try block code does not execute -
i not understand why code in try block not execute. compilation error says when use these variables after try block, may not initialized.
double star, planet, poslife, actlife, intellife, comm, length; try{ star = double.parsedouble(factor.elementat(0).gettext()); planet = double.parsedouble(factor.elementat(1).gettext()); poslife = double.parsedouble(factor.elementat(2).gettext()); actlife = double.parsedouble(factor.elementat(3).gettext()); intellife = double.parsedouble(factor.elementat(4).gettext()); comm = double.parsedouble(factor.elementat(5).gettext()); length = double.parsedouble(factor.elementat(6).gettext()); } catch(numberformatexception e){ system.err.println("numberformatexception"); }
first, variables define in try block should not visible outside try block ; believe must have double star;
etc. before try.
now, i'll assume code more following, because error spoke of not occur code gave us:
double a; try { = double.parsedouble(/* blah */); } catch (numberformatexception e) { system.err.println("numberformatexception"); }
here, after execution of block of code, a
may uninitialized. indeed, if error occured in double.parsedouble
, assignment a
skipped jump catch block, not return.
thus, after above block of code, a
may uninitialized, hence error message.
to fix it, should remove types before variables inside try
block, , either provide default value in case it's impossible parse double, or, if exception cannot recovered in this scope, not catch in first place.
Comments
Post a Comment