我得到了一个try catch finally java问题。代码是这样的:
package com.test;
public class TestExamples {
public int testFinally(int inputNum) {
int returnNumber = inputNum;
try {
returnNumber++;
return returnNumber;
} finally {
returnNumber++;
}
}
public StringBuilder testFinallyString() {
StringBuilder builder = new StringBuilder();
try {
builder.append("cool");
return builder.append("try");
} finally {
builder.append("finally");
}
}
public static void main(String[] args) {
TestExamples testExamples = new TestExamples();
System.out.println("The result of testFinally is " + testExamples.testFinally(5));
System.out.println("The test of testFinallyString is " + testExamples.testFinallyString());
}
}
结果:
testFinally 的结果是 6 testFinallyString
的测试是cooltryfinally
如果 finally 每次都执行,那为什么 testFinally 是 6?我有点困惑,最终代码块不会导致返回的数字增加。请有人能更清楚地说明根本原因是什么。