为什么我们最后使用的块? [英] Why do we use finally blocks?
本文介绍了为什么我们最后使用的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
据我所知道的,下面的两个code段将达到同样的目的。为什么有最后
在所有块?
code答:
尝试{/ *一些code * /}
赶上{/ *异常处理code * /}
最后{/ *清理code * /}
code B:
尝试{/ *一些code * /}
赶上{/ *异常处理code * /}
//清理code
解决方案
- 如果一个异常你不处理被抛出,会发生什么? (我希望你不要再追
的Throwable
...) - 如果你从try块内返回,会发生什么?
- 如果catch块抛出一个异常,会发生什么 ?
A 最后
块可以确保的然而的退出该块(模明确中止的整个过程中的一些方法),它会得到执行。这是对资源的确定性清理重要。
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally
blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
解决方案
- What happens if an exception you're not handling gets thrown? (I hope you're not catching
Throwable
...) - What happens if you return from inside the try block?
- What happens if the catch block throws an exception?
A finally
block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
这篇关于为什么我们最后使用的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文