What is the use of having try-with-finally, with out any catch block?
There is no use case as such.
There may be situations where we have to release system resources carefully, and our code is full of loops, return, and break statements. In those scenarios we can use finally block to make sure that all resources will be released properly.
We can't use try with out catch block.
We can use try with finally block but at least one catch block should be there.
System resources like sockets, files have to be closed properly after using, as system will have limited such kind of resources.
Assume a scenario where in a function we are opening some sockets and files, and that function has got lot of nested loops with multiple return, break statements. If the code is in such a messy state, there might be some chances where programmer might not check all the scenarios and end up in "failing to release the important resources" which he is using in that function.
To avoid such kind of error prone scenarios, we keep all loops, returns, breaks in a try block and release all system resources in finally block which is attached to that try block. Now java run time system will ensure that it will always execute finally block and cleans the resources properly before exiting from the function.
Back To Top