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
- ...