问题描述
是否有关于是否使用 finalize()
清除对象的详细信息,如果该对象的构造函数是异常。
Are there any details on whether or not an object is cleaned up using finalize()
if that object's constructor thew an exception.
当调用这个方法时,出了名的错误。根据手册:
When this method is called is notoriously ill defined. According to the manual:
我没有能够以这种方式触发finalize方法。有没有人知道它是不是被调用了,或者在某些情况下是在构造函数初始化对象后调用的(这是一个异常)。
I've not been able to trigger the finalize method in this way. Does anyone know if it is garunteed NOT to be called or if it is in some cases called after the constructor failed to initialize the object (thew an exception).
我问这是因为我有一个不能清理两次的物体。我试图了解在抛出异常之前清理是否安全,或者我是否必须为 finalize()
留下标记以有效地跳过并且什么也不做。
I ask this because I have an object which must not be cleaned up twice. I'm trying to understand if it is safe to clean up before throwing the exception or if I must leave a marker for finalize()
to effectively skip and do nothing.
推荐答案
我的测试显示它可以
public class Test1 {
Test1() {
throw new RuntimeException();
}
@Override
protected void finalize() throws Throwable {
System.out.println("finalized");
}
public static void main(String[] args) throws Exception {
try {
new Test1();
} catch (RuntimeException e) {
e.printStackTrace();
}
System.gc();
Thread.sleep(1000);
}
}
打印
java.lang.RuntimeException
at test.Test1.<init>(Test1.java:13)
at test.Test1.main(Test1.java:24)
finalized
它位于Java HostSpot Client VM 1.7.0_03上
it is on Java HostSpot Client VM 1.7.0_03
这篇关于在构造函数抛出异常后可以调用finalize吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!