Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type with try-catch-finally [duplicate]

Tags:

java

I have tried the following code snippet:

private Integer getnumber() {
    Integer i = null;
    try {
        i = new Integer(5);
        return i;
    } catch(Exception e) {
        return 0;
    } finally {
        i = new Integer(7);
    }
}

This method returns 5 and not 7.

Why it returns 5 and not 7?

Thanks in advance.

like image 256
user2669894 Avatar asked Oct 22 '22 03:10

user2669894


1 Answers

This happens because the finally block of a try..catch..finally runs after the code within the try..catch has completed (be it successfully or not); in the case of your code this is when the return i has occured.

Because of this behaviour the value of i has already been placed into the return variable of the method before you then assign the new value of 7 to it. The following would work:

private Integer getnumber(){
  Integer i = null;
  try {
    i = new Integer(5);
  }
  catch(Exception e){
    i = new Integer(0);
  }
  finally{
    i = new Integer(7);
  }
  return i;
}
like image 104
melodiouscode Avatar answered Oct 23 '22 20:10

melodiouscode