Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?
To make my question m
With Java 1.7 released, you now have the additional option of using the try-with-resources
block. For example,
public class Closeable implements AutoCloseable {
@Override
public void close() {
System.out.println("closing...");
}
public static void main(String[] args) {
try (Closeable c = new Closeable()) {
System.out.println("trying...");
throw new Exception("throwing...");
}
catch (Exception e) {
System.out.println("catching...");
}
finally {
System.out.println("finalizing...");
}
}
}
If you execute this class, c.close()
will be executed when the try
block is left, and before the catch
and finally
blocks are executed. Unlike in the case of the finalize()
method, close()
is guaranteed to be executed. However, there is no need of executing it explicitly in the finally
clause.