wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Find the unreachable statement in this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Find the unreachable statement in this code" Watch "Find the unreachable statement in this code" New topic
Author

Find the unreachable statement in this code

Shailendra Guggali
Ranch Hand

Joined: Feb 01, 2001
Posts: 86
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

Joined: Feb 01, 2001
Posts: 130
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.


Sun Certified Programmer for Java 2 Platform
Ganesh Narayanan
Greenhorn

Joined: Jan 29, 2001
Posts: 7
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

Joined: Feb 01, 2001
Posts: 86
hi nat , Ganesh
statment no. 3 is also not reached - pls try to figure out how and why???
Priya Kannan
Ranch Hand

Joined: Jan 19, 2001
Posts: 72
Hi Shailendra,
If statement #2 throws an exception ,control passes to the catch block.So #3 is unreachable.
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
as you said priya, if! but that is not a certainity, and yours is not an answer.
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
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

Joined: Jan 26, 2001
Posts: 439
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.


Val SCJP <BR>going for SCJD
Priya Kannan
Ranch Hand

Joined: Jan 19, 2001
Posts: 72
Aye,Aye,sir!
Code compiles smoothly with #7 commented out.
Hey Anshuman, thanks for correcting me.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Find the unreachable statement in this code
 
Similar Threads
parseFloat and Float.NaN??
Exam on Monday -- pl help
unreachable code in 'finally'
JQ+ Question ID :957639266007
exception flow