这个问题触发一用户可见的例外是Exception in finalize method和类似的问题相反。在Finalize方法
我创建一个AutoCloseable
类构成了严重的风险,如果没有正确关闭。在这种情况下,我正在寻求失败 - 以便用户不会意外地忘记这么做。
我意识到并同意,一般最佳做法是让Closeable
优雅地失败并尽其所能缓解来电者的错误,但在这种情况下,来电者不会想错过此操作。如果你在概念上不同意这个想法,我会很感激你的反馈,但在这种情况下,考虑一个关于Java内部的学术练习的问题。
我想如果我调用IllegalStateException
并打断用户,如果我的类的finalize()
方法被调用,并且实例还没有被清理。但finalize()
显式吞下未捕获的异常,这使得这个棘手。导致用户从finalize()
方法中看到的RuntimeException
的最佳方法是什么?
这里有一个演示类的东西,我这么远:
public class SeriouslyCloseable implements AutoCloseable {
// We construct an Exception when the class is initialized, so that the stack
// trace informs where the class was created, rather than where it is finalized
private final IllegalStateException leftUnclosed = new IllegalStateException(
"SEVERE: "+getClass().getName()+" was not properly closed after use");
private boolean safelyClosed = false;
@Override
public void close() {
// do work
safelyClosed = true;
}
@Override
protected void finalize() throws IllegalStateException {
if(!safelyClosed) {
// This is suppressed by the GC
throw leftUnclosed;
}
}
}
注:我知道也是finalize()
不能保证运行,所以任何事情我身边这个方法实施并非绝对不会发生。我仍然喜欢,如果GC给我们机会,可能会发生。