The problem is that the bracket after the println in finally is backwards, which effectively ends the finally block before the return happens. Therefore you have a return statement outside of any method and the compiler complains.

hi shabbir there were a few more errors so here is the compileable code and the return f; statement should be in the finally clause as the compiler sees the return statement after the finally clause even though u've put the same return statement in the try block. so the compiler sort expects an exception to occur because u've put in try catch and finally blocks but if an exception does occur the finally block shoudn't be run as u have a return statement in the catch block, but if u didn't have the return statement in the catch block only the finally block will be run but the return was after the finally block. hope this is clear here's the correct code: public class tester{ public float parseFloat(String s){ float f = 0.0f,f1=0.0f; try{ f = Float.valueOf(s).floatValue(); return f; } catch(NumberFormatException fex){ System.out.println("Invalid input" + s); f1 = Float.NaN; return f1; } finally{ System.out.println("finally"); return f;} } }

shabbir zakir
Ranch Hand

Joined: Nov 12, 2000
Posts: 183

posted Mar 22, 2001 11:30:00

0

hi! Thanks lee & cindy for your explanations. It will more clear if someone gives more of this type of error prone codes. Thanks in advance

Hi Shabbir, The main reason the 'return' stmt in the main()method won't be reached is that, the control will be returned back(exception or no exception) to the calling method because of your 'return' stmts in both the try and catch blocks. And of course before either return control goes to the finally block. Comment out either one of these 'return' stmts and ur code should work. And as Lee pointed out, there were other errors too. Here is the code- public class x { public float parseFloat(String s) { float f = 0.0f,f1 = 0.0f; try { f = Float.valueOf(s).floatValue(); //return f; } catch(NumberFormatException fe) { System.out.println("Invalid input" + s); f1 = Float.NaN; return f1; } finally{ System.out.println("finally"); } return f; } }