Creating a destructor in Java

In C++, a destructor typically cleans up resources (dynamically allocated memory, open file handlers, …). In Java, the garbage collector automatically frees up a dynamically created object whenever there are no more references pointing to that object. Sometimes, it may occur that you want to free up extra resources. You could then implement the protected void finalize() method which will be executed when the garbage collector decides to free up the object. However, this method implies the behavior of your program is totally dependent on the garbage collector. A more reliable way is to use the try / catch / finally block to clean up extra resources because you can be certain that the finally block will be executed regardless of any exceptions thrown.