Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to get return value in finally statement?

Tags:

java

finally

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. 
}
like image 744
BlueDolphin Avatar asked Jan 08 '23 12:01

BlueDolphin


2 Answers

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;
like image 102
Brett Haines Avatar answered Jan 12 '23 00:01

Brett Haines


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;
}
like image 30
Makoto Avatar answered Jan 11 '23 22:01

Makoto