我聽說,有可能寫這樣一些代碼這個當Java對象部分初始化(構造函數中發生異常)
SomeClass obj = null;
try {
obj = new SomeClass();
} catch (Exception e) {
...
}
...
if (obj != null) { // here it holds true
...
}
有人可以請解釋一下,是不可能的,並在什麼情況下如果我們假設構造函數SomeClass 可能會拋出異常?
又如:
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
public class Sample{
static class A {
public static A s;
public A(Collection c) {
c.add(this);
s = this;
throw new RuntimeException();
}
}
@Test
public void testResource() throws Exception {
List l = new ArrayList();
A a = null;
try {
a = new A(l);
fail("Oops");
} catch (Throwable e) {
}
assertTrue(l.size() == 1);
assertNull(a);
assertNotNull(A.s);
assertNotNull(l.get(0));
}
}
你能發佈一個鏈接到可疑信息的來源嗎? – 2011-05-06 10:12:57
@Laurent:mat be this:http://stackoverflow.com/questions/5909818/java-exception-thrown-in-constructor-can-my-object-still-be-created – 2011-05-06 10:14:29