This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
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
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply 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!
 
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.
 
subject: JQ+ and confusion with try/catch/finally
 
Similar Threads
Exception Handling
unreachable code in 'finally'
JQPlus Question
return
Unreachable Code in try/catch ? why????