Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

JQ+ and confusion with try/catch/finally  RSS feed

 
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?
 
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!
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!