-1

I'm studying for the OCA exam and I do not understand why the last line in parseFloat() is unreachable, while the last line in go() is not. Except for the return types, I do not see much of a difference.

  public float parseFloat(String s) {
        float f = 0.0F;
        try {
            f = Float.valueOf(s).floatValue();
            return f;
        } catch (NumberFormatException e) {
            f = Float.NaN;
            return f;
        } finally {
            return f;
        }
        System.out.println(""); //unreachable statement   
    }    
    public void go() {
        System.out.println("A");
        try {
            System.out.println(3 / 0);
        } catch (ArithmeticException e) {
            System.out.println("b");
        } finally {
            System.out.println("c");
        }
        System.out.println("d"); //reachable statement
    }
Helenesh
  • 3,999
  • 2
  • 21
  • 36
  • 1
    Read https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html. Returning from a method stops the execution of the method. Printing something on the screen does not. There is a huge difference. – JB Nizet Sep 04 '15 at 15:00
  • 3
    I wish I had that exam, looks easy ( ; – Derrops Sep 04 '15 at 15:00
  • @Helenesh there is no return at all in the second snippet. The statement is unreachable in the first snippet because there is a return BEFORE that print statement. There is no return BEFORE the print statement in the second one. – JB Nizet Sep 04 '15 at 15:19

1 Answers1

4

It is because you always return before calling that statement. Remember, that finally is always invoked - even if you use return.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • 1
    returning from a catch block is fine: if it's executed, then the try block hasn't possibly returned anything. It's returning from a finally block that should be avoided, since it's executed even if the try block has already returned something. – JB Nizet Sep 04 '15 at 15:02
  • I believe it *can be* fine to return anywhere, if you know what you are doing :) (it is valid Java code after all). Nevertheless, in my own code I tend to not return either in `catch` or `finally`. – meskobalazs Sep 04 '15 at 15:11