Monday, April 26, 2010

Java Basics #001

Case i Case ii

try {

        return 1;

} catch (Exception ex) {

return 2;

} finally {

return 3;

}

try {

       throw new exception(“test”);

} catch (Exception ex) {

       return 2;

} finally {

       return 3;

}

Q. Consider the above block of code within a method. What will be returned in these cases?

Source : Avaya

10 comments:

  1. whoever wrote this should be hung

    ReplyDelete
  2. It would always return 3, i.e., execute the finally block. It would never return 1 or 2. "finally" gets executed irrespective of any exception is thrown.

    ReplyDelete
  3. buy why? what happens to the other returns during execution?

    ReplyDelete
  4. Please read the comment: "finally" gets executed irrespective of any exception is thrown. So, in Case I when there is no exception, before executing "return 1" statement it would execute the finally block. Since in the finally block you have "return 3" the return statement. Output Case II would also be identical to Case I.
    To summarize: "If there is a return statement within the finally block, it will trump any other return from the regular block."

    That's a BAD PRACTICE anyways.... :)

    Check out this link also: http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

    ReplyDelete
  5. More Gyan on the above question: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-hood.html?page=1

    ReplyDelete
  6. Techie, any comments on why the code below returns 1 instead of 3???

    int i=0;
    try{
    i=1;
    return i;
    } catch(Exception ex) {
    i=2;
    return i;
    }finally {
    i=3;
    }

    ReplyDelete
  7. Refer: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-hood.html?page=4

    "Note that the bytecodes that implement the return statement store a copy of the return value into local variable 3 before jumping to the miniature subroutine that represents the second finally clause. Then, after the miniature subroutine returns (in this case it never does, because the continue is always executed), the return value is retrieved from local variable 3 and returned. This highlights the way the JVM returns values when finally clauses are also executed. Rather than returning the value of i after the finally clause is executed, the JVM will return the value that i had just before the finally clause was executed. This means that even if the finally clause changes the value of i, the method will still return the value that i had when the return statement was first reached, before the finally clause was invoked. If you wanted the finally clause to be able to change the return value of the method, you would have to put an actual return statement with the new return value into the finally clause itself."

    ReplyDelete
  8. The javaworld link posted above is awesome!!

    ReplyDelete

Google Analytics - Active