Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JQ+ and confusion with try/catch/finally

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following is a supposedly roboust method to parse an input for a float....
public float parseFloat(String s)
{
float f = 0.0f;
try
{
f = Float.valueOf(s).floatValue();
return f ;
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid input " + s);
f = Float.NaN ;
return f;
}
finally { System.out.println("finally"); }
return f ;
}
I also tried commenting out the 'return f;' statment in the try block .. but it still gives me the same error - what concept am I missing here??
Thank you!

Now the above code will not compile because of the unreachable 'return f;' statement AFTER the finally block. I swear I've had questions similar where a return following a finally block would work .. but I can't remember how it would work.
Rewriting the finally block and the last bracket:
finally {
System.out.println("finally");
}
return f;
}
f is declared as a float variable .. so why can't it just return 0.0f?
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think you should have all the return statements because they are not needed. If you have a return in your try block, your finally code will still get executed. This has returns all over it, so I would write this so the return is after the try..catch..finally block.
But anyway, to answer your question, you can have a return after the finally block, but you have one in the try and catch block and since the only error that can be thrown is NumberFormatException, either the code will work, so you hit the return in the try block, or it will throw a NumberFormatException, so it will hit the return in the catch block. Either way, it will never get to the return after the finally block.
Bill
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok I get it now - thanks for the explanation bill!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic