Я написал семь тестовых примеров для понимания поведения блока finally
. Какова логика работы finally
?Понимание блока «finally»
package core;
public class Test {
public static void main(String[] args) {
new Test().testFinally();
}
public void testFinally() {
System.out.println("One = " + tryOne());
System.out.println("Two = " + tryTwo());
System.out.println("Three = " + tryThree());
System.out.println("Four = " + tryFour());
System.out.println("Five = " + tryFive());
System.out.println("Six = " + trySix());
System.out.println("Seven = " + trySeven());
}
protected StringBuilder tryOne() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
}
finally {
builder = null;
}
}
protected String tryTwo() {
String builder = "Cool";
try {
return builder += "Return";
}
finally {
builder = null;
}
}
protected int tryThree() {
int builder = 99;
try {
return builder += 1;
}
finally {
builder = 0;
}
}
protected StringBuilder tryFour() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
}
finally {
builder.append("+1");
}
}
protected int tryFive() {
int count = 0;
try {
count = 99;
}
finally {
count++;
}
return count;
}
protected int trySix() {
int count = 0;
try {
count = 99;
}
finally {
count = 1;
}
return count;
}
protected int trySeven() {
int count = 0;
try {
count = 99;
return count;
}
finally {
count++;
}
}
}
Почему builder = null
не работает?
Почему builder.append("+1")
работа тогда count++
(в trySeven()) делает не работу?
Символ 'StringBuilder' ссылка, безусловно, может быть нулевым. Объявлен 'count'. –
даже после создания экземпляра? –
Каждый раз. 'StringBuilder sb = new StringBuilder(); sb = null; 'является юридическим кодом (даже если это не очень полезно в этом случае). StringBuilder - это ссылочный тип, а * любой * ссылочный тип может быть нулевым. – cHao