And moreover instead of writing the code in finally block we can simply catch the exception in catch block and whatever resources we need to clean we can write it after the try-catch block. What is the use of that finally block then?
Asked
Active
Viewed 90 times
0
-
2The `finally` block has uses besides cleaning up resources. Try-with-resources captures _some_, but not all, of the use cases for `finally`. – Louis Wasserman Nov 10 '20 at 18:26
-
[The documentation for Lock](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/locks/Lock.html) has an example use of `finally`. – VGR Nov 11 '20 at 00:43
2 Answers
1
You should only catch exceptions if you intend to handle them, which you may not want to do under certain circumstances (e.g. if you want the exception to be handled elsewhere in code).
Also, automatic resource management doesn't guarantee that there isn't some additional cleanup that's specific to your application that needs to happen.

EJoshuaS - Stand with Ukraine
- 11,977
- 56
- 49
- 78
0
You can also use a finally
block without a catch
public void doSomething() throws ActionException
{
FileAction action = null;
try
{
action = new FileAction();
someCode();
}
finally
{
if ( action != null )
action.close();
}
}
So the finally
will always be executed regardless if an exception is thrown

Big Guy
- 332
- 1
- 13