I\'ve written seven test cases for understanding the behavior of the finally
block. What is the logic behind how finally
works?
pac
Consider what the compiler is actually doing for the return statement, for instance in tryOne(): it copies a reference to builder
back to the calling function's environment. After it's done this, but before control goes back to the calling function, the finally block executes. So you have something more like this, in practice:
protected StringBuilder tryOne() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
builder.append("Return");
StringBuilder temp = builder;
return temp;
} finally {
builder = null;
}
}
Or, in terms of the order that statements actually get executed (ignoring possible exceptions, of course), it looks more like this:
protected StringBuilder tryOne() {
StringBuilder builder = new StringBuilder();
builder.append("Cool");
builder.append("Return");
StringBuilder temp = builder;
builder = null;
return temp;
}
So setting builder = null
does run, it just doesn't do anything useful. However, running builder.append("something")
will have a visible effect, since both temp and builder refer to the same (mutable) object.
Likewise, what's really happening in trySeven() is something more like this:
protected int trySeven() {
int count = 0;
count = 99;
int temp = count;
count++;
return temp;
}
In this case, since we're dealing with an int, the copies are independent, so incrementing one doesn't affect the other.
All that said, the fact remains that putting return statements in a try-finally block is quite clearly confusing, so if you've got any kind of choice in the matter, you'd be better off rewriting things so that all your return statements are outside any try-finally blocks.