Assigning null to variable in finally block
This question already has an answer here:
Basically, what Java does is the following:
StringBuilder valueToReturn = builder.append("Passed!!!");
executeFinallyBlock();
return valueToReturn;
Whatever you're doing inside the finally block, Java has kept a reference to the value to return, and returns that reference. So it becomes:
StringBuilder valueToReturn = builder.append("Passed!!!");
builder = null;
return valueToReturn;
The answer is simple.
Finally block will be executed for sure, since you are not returning any value from it, the try block returned value will be passed to original caller
try {
builder.append("Test ");
return builder.append("Passed!!!");
} finally {
builder = null;
}
Thus, you are getting "Test Passed!!!"
Changing the code to
StringBuilder builder = new StringBuilder();
try {
builder.append("Test ");
return builder.append("Passed!!!");
} finally {
return null;
}
will certainly print "null" as you expected
链接地址: http://www.djcxy.com/p/73712.html上一篇: 为什么空的catch块是一个坏主意?
下一篇: 在finally块中将null指定给变量
