方法终结和异常
我不太明白当GC从内存中回收对象时,异常会被忽略。
如果我在 Finalize 方法中使用 try/catch
,我会发现它总是被执行......那么在哪些情况下不会抛出异常?
谢谢。
I don't understand very well when an exception is ignored by the GC when it reclaims from the memory an object.
If I have a try/catch
into a finalize method I see it is always executed... so which are the cases where the exception is not thrown?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
finalize
方法由终结器线程运行。如果抛出异常,终结器将忽略它(吞掉它)。否则,终结器线程将会死亡。这适用于抛出但未被代码捕获的异常(在
finalize()
内)。如果您捕获了异常,则一切照常。the
finalize
method is run by the finalizer thread. if you throw exception, the finalizer will ignore it (swallow it). Otherwise, the finalizer thread would die.This applies to exceptions that are thrown and not caught by your code (inside
finalize()
). If you catch the exception, it is business as usual.两个现有的答案似乎表明终结器将忽略任何未捕获的异常。这似乎与此处的答案相矛盾: finalize 方法中的异常 似乎有正确的引用JSL。它表示未捕获的异常将中止相关对象的终结(可能泄漏资源),但终结器线程本身将继续终结其他对象。这与经验结果相符。
The two existing answers appear to say that the finalizer will ignore any uncaught exceptions. This appears to contradict the answer here: Exception in finalize method which appears to have a correct reference to the JSL. It says that uncaught exceptions will abort the finalization of the object concerned (possibly leaking resources) but that the finalizer thread itself will continue finalizing other objects. This matches empirical results.
这意味着从
finalize
方法抛出的任何异常都将被忽略。然而,它内部的异常仍然照常工作。It means that any exception thrown from the
finalize
method is ignored. However, exceptions inside it still work as usual.