-1

Can we avoid finally block if we do resource cleanup in both try and catch together?

E.g. 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?

Nadeem
  • 121
  • 2
  • 13
  • Because code repetition is not nice – Michal Polovka Nov 26 '18 at 11:36
  • 2
    Why would you not want to use `finally`? There seems to be the underlying assumption that it is *worth* avoiding. – Andy Turner Nov 26 '18 at 11:39
  • 1
    In this case your `catch` clause does nothing except close the database. Doesn't even log the error. If your `catch` clause did more things (as it would in a real application), then you run the risk of another exception occurring before `db.close()` is reached. – khelwood Nov 26 '18 at 11:44

5 Answers5

2

Just use try-with-resources:

try(Connection db = getConnection()){
    //perform stuff
}

once the try block has finished processing the Connection will be closed.

Lorelorelore
  • 3,335
  • 8
  • 29
  • 40
0

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

Akceptor
  • 1,914
  • 3
  • 26
  • 31
0

This works as expected, however, it repeats code, which means that if you want to change the "final part code" you will have to change the code twice, instead of once if you put it in a finally block.

TheWildHealer
  • 1,546
  • 1
  • 15
  • 26
0

Yes it will work. Finally block is basically used for the common operations in the try/catch. But think about it you have 10-20 common statement in both try and catch. Then what it will look like? Finally block help you to remove redundancy of your code.

0

Use try-with-resources wherever possible or try-finally (try-catch-finally).

Can we avoid finally block if we do resource cleanup in both try and catch together?

Why? You could, by substituting a well working and for this purpose designed java idiom by errorneous code and by using some antipatterns.

Assuming, your are going to log or handle exceptions in real life, this is why your code is not the same:

Not working:

  • your connection is not always closed, since you are only handling exceptions, no errors or throwables

Some antipatterns:

  • You are re-inventing the wheel
  • DRY (don't repeat yourself)
  • Catch the most specific exceptions first; avoid handling Exception, Error or Throwable in general
  • be aware of swallowing exceptions (possible with finally, too!), try-with-resources is using suppressed exceptions for this
  • ...
Frito
  • 446
  • 2
  • 12