It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes JQ+ and confusion with try/catch/finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "JQ+ and confusion with try/catch/finally" Watch "JQ+ and confusion with try/catch/finally" New topic
Author

JQ+ and confusion with try/catch/finally

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jun 30, 2000
Posts: 1070
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

Joined: Nov 22, 2008
Posts: 18944
Ok I get it now - thanks for the explanation bill!
 
 
subject: JQ+ and confusion with try/catch/finally