DEV Community

EKaterinaTR
EKaterinaTR

Posted on

Averting resource leaks due to an exception/error(not only about try-with-resources!!!)

I came across a project on Github (https://github.com/mabrarov/exception-safety), which describes an approach to prevent resource leaks due to throwing an error or exception.
The main difference from simple try-with-resources (If you don't know what it is: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) is that resource remains opened if an exception or error doesn't throw. It saves time for creating/opening resources every time.
An instance of the Guard is put in try-with-resources instead of a real resource.
Firstly, in the try-with-resources block, the guard gets a link to a resource. Then we do whatever we want with the resource, if an exception/error occurs, the guard closes the resource.
At the end of the block, we should don't forget about releasing of the resources: the guard drops its link to the resource.
I think it can be a powerful thing, what about you? Maybe are you doing with such cases in another way?

Top comments (0)