我最后应该在Java的try-catch中使用finally块 [英] When should I use the finally-block in Java's try-catch-finally

查看:136
本文介绍了我最后应该在Java的try-catch中使用finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候应该使用代码段A而不是代码段B(即使用代码段A有什么好处)?

When should I use code snippet A instead of snippet B (i.e. what are the benefits of using snippet A)?:

代码段A: strong>

Snippet A:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}
finally {
    //codeblock C
}

片段B:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}

//codeblock C


推荐答案

如果您有代码必须执行,没有例外被抛出。

Use a finally block if you have code that must execute regardless of whether or not an exception is thrown.

清理数据库连接等稀缺资源是一个很好的例子。

Cleaning up scarce resources like database connections are a good example.

这篇关于我最后应该在Java的try-catch中使用finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆