[英]Can we avoid finally block if we do resource cleanup in both try and catch together?
Can we avoid finally block if we do resource cleanup in both try and catch together ? 如果我们同时尝试进行资源清理,是否可以避免finally阻塞?
Eg Can we do something like this and not use finally? 例如,我们可以做这样的事情并且最终不使用吗?
try{
// Some statements
db.close();
}catch(Exception e){
db.close();
}
Will it work as expected? 它会按预期工作吗? If Yes then Why should or shouldn't we use it? 如果是,那么我们为什么应该或不应该使用它?
Just use try-with-resources
: 只需使用try-with-resources
:
try(Connection db = getConnection()){
//perform stuff
}
once the try
block has finished processing the Connection
will be closed. 一旦try
块完成处理, Connection
将关闭。
Yes we can. 我们可以。 But why you want to call the same code twice instead of having single call which will be executed in any case? 但是,为什么您要两次调用相同的代码,而不是要在任何情况下都执行一次调用?
For the best practices see this question Java try/catch/finally best practices while acquiring/closing resources 有关最佳做法,请参见以下问题, Java在获取/关闭资源时会尝试/捕获/最终最佳做法
这可以按预期工作,但是它会重复代码,这意味着,如果您想更改“最终零件代码”,则必须将代码更改两次,而不是将其放入finally块中一次。
Yes it will work. 是的,它将起作用。 Finally block is basically used for the common operations in the try/catch . finally块基本上用于try / catch中的常见操作。 But think about it you have 10-20 common statement in both try and catch. 但是考虑一下,您在尝试和抓住中都有10到20条共同的陈述。 Then what it will look like? 那会是什么样子? Finally block help you to remove redundancy of your code. 最终阻止可帮助您删除代码的冗余。
Use try-with-resources wherever possible or try-finally (try-catch-finally). 尽可能使用try-with-resources或最终尝试(try-catch-finally)。
Can we avoid finally block if we do resource cleanup in both try and catch together? 如果我们同时尝试进行资源清理,是否可以避免finally阻塞?
Why? 为什么? You could, by substituting a well working and for this purpose designed java idiom by errorneous code and by using some antipatterns. 您可以通过使用错误的代码并使用一些反模式来替代运行良好且为此目的设计的Java惯用语。
Assuming, your are going to log or handle exceptions in real life, this is why your code is not the same: 假设您将在现实生活中记录或处理异常,这就是为什么您的代码不同的原因:
Not working: 无法运作:
Some antipatterns: 一些反模式:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.