BlueDolphin
BlueDolphin

Reputation: 9765

Is there anyway to get return value in finally statement?

In some legacy code, there are several places to return values. I'd like to log the return value. Is it possible to get the return value in the finally statement?

For example:

try {
   if (v == 1) { 
      return 3;
   } else if (v == 3) {
      return x + 2;
   }
} finally {
   // I need to know the return value here, either 3 or x + 2. 
}

Upvotes: 4

Views: 2331

Answers (2)

Brett Haines
Brett Haines

Reputation: 184

Once return is called, everything else in that function is skipped. If you want to know what the value is there, you're better off saving your 3 or x+2 in a variable outside the scope of your try block.

int ret = -1;
try {
    if (v == 1) {
        ret = 3;
    }
    else if (v == 3) {
        ret = x + 2;
    }
}
finally {
    System.out.println("The value of ret is " + ret);
}
return ret;

Upvotes: 7

Makoto
Makoto

Reputation: 106470

No; a finally block doesn't have context into the previous return value.

Your best bet is to store the value off in a variable, log the variable, and return the variable later.

int result = 0;
if (v == 1) {
  result = 3;
  log.debug(result);
  return result;
} else if (v == 3) {
  result = x + 2;
  log.debug(result);
  return result;
}

Upvotes: 1

Related Questions