这个问题与finalize 方法中的 Exception和类似问题相反。
我正在创建一个AutoCloseable
如果没有正确关闭会带来严重风险的课程。我希望在这种情况下进行故障排除,以免用户不小心忘记这样做。
我意识到并同意,一般的最佳实践是让Closeable
s 优雅地失败并尽最大努力减轻调用者的错误,但在这种情况下,调用者不想错过这一点。如果您在概念上不同意这个想法,我会很感激您的反馈,但在这种情况下,请将该问题视为关于 Java 内部的学术练习。
如果我的类的方法被调用并且实例尚未被清理,我的设想是引发IllegalStateException
并中断用户。finalize()
然而finalize()
,明确地吞下未捕获的异常,这使得这很棘手。导致RuntimeException
用户从该finalize()
方法中看到的最佳方法是什么?
这是到目前为止我所拥有的演示类:
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 给我们机会,我仍然希望它可能发生。