gpt4 book ai didi

java - Java中的对象被部分初始化时(构造函数发生异常)

转载 作者:行者123 更新时间:2023-12-01 14:07:12 24 4
gpt4 key购买 nike

听说可以这样写一些代码

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));
}

}

最佳答案

首先声明并初始化一个变量。

SomeClass obj = null;

在以下几行中,您 (1) 创建一个新实例并 (2) 存储引用。

try {
obj = new SomeClass();
} catch ( Exception e ) {
...
}

现在我们假设,实例化(第 1 步)失败并抛出异常:JVM 将继续处理该异常的下一个 catch block 。所以第 2 步不会被执行,变量会保持它的实际状态。

现在是可能实例已部分初始化。老实说,我不知道,那是 JVM 内部的。但是由于没有任何东西引用这个部分初始化的实例,它会在下一次被 gc'd 。

关于java - Java中的对象被部分初始化时(构造函数发生异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5909902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com