• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Find the unreachable statement in this code

 
Shailendra Guggali
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What can be done to get the following code compile and run?
public float parseFloat( String s )
{
float f = 0.0f; // 1
try
{
f = Float.valueOf( s ).floatValue(); // 2
return f ; // 3
}
catch(NumberFormatException nfe)
{
f = Float.NaN ; // 4
return f; // 5
}
finally {
return f; // 6
}
return f ; // 7
}
I thought the unreachable statements were //7 after return in finally, //4 //5 as they may not be reached if not exception is thrown.
Can someone explain which all are unreachable and why???
 
natarajan meghanathan
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
only statement 7 is unreached. since u r returning from each block in the method, the control does not go that statement in any of the possible executions.
 
Ganesh Narayanan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only line 7 of the code is unreached,since it has reached the finally block.
But the return value at the end of the function is required since the return type for the method is specified otherwise it fires an eroor
 
Shailendra Guggali
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi nat , Ganesh
statment no. 3 is also not reached - pls try to figure out how and why???
 
Priya Kannan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shailendra,
If statement #2 throws an exception ,control passes to the catch block.So #3 is unreachable.
 
Anshuman Acharya
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as you said priya, if! but that is not a certainity, and yours is not an answer.
 
Anshuman Acharya
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code compiles for me if i remove statement 7...
i am using version 1.2, which one are you using shailendra?
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think only 7th must be removed finally will always garanteed to run no matter what so last return statement will never get to run.
 
Priya Kannan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aye,Aye,sir!
Code compiles smoothly with #7 commented out.
Hey Anshuman, thanks for correcting me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic