Reputation:
I'm preparing for OCA Java exam and got this question wrong. I can't see why the return
statement is unreachable. My thinking is that even if an exception is thrown it will be caught, the statement in the finally block executed and then the return statement is executed, or is it the case that the thread does not execute the return statement if an exception is thrown? More generally, can somebody explain the rules of what happens in the case of an exception being fired and in which cases statements after the finally block are executed or not. For some questions I am getting this correct and for others I am not so I am not clear on the exact compiler rules here.
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 ;
}
Upvotes: 0
Views: 216
Reputation: 5039
so there might be a theoretical case, where your code would make sense: If the code inside the try{} block would throw any other exception besides NumberFormatException. This is only possible, if it is an unchecked exception (the ones you are not required to catch). The compiler cannot know or check this, therefore such code is not allowed unless you write a second catch block for it. (if you are confused now: forget what I said, it's not important for your task)
here is a sample of such a case:
public float parseFloat(String s){
float f = 0.0f;
try{
SomeOtherClass.doStuffWhichFailsWithRuntimeException();
return f;
}
catch(NumberFormatException nfe){
// will not run, because the thrown exception is not of type NumberFormatException
}catch(Exception e){
// any other failure besides NumberFormatException
// considered bad practice: If you do not know what fails, do not try to recover from it, it's most likely very bad.
return f;
}
finally {
// this will run after the catch block was run
System.out.println("finally");
}
// theoretically reachable, but compiler does not allow it because he cannot check it.
//return f ;
}
Upvotes: 3
Reputation: 1367
If an exception is occured then catch block runs, f is returned and finally block runs next. The last
return f;
will never be reached.
Upvotes: 1