public void foo() {And you can be comfortable that, if written correctly, ResourceIntesiveClass' destructor will be called and all resources freed when ric goes out of scope, regardless of whether it was under control or because of an exception thrown by ResourceIntensiveClass::exceptionRiddledFunction().
ResourceIntensiveClass ric = new ResourceIntensiveClass("have bugs");
ric.initiateResourceLockingStuff();
ric.exceptionRiddledFunction();
}
Unfortunately, when Java was being designed, the designers seem to want to get rid of every aspect of C++ that gave people trouble. Many people have trouble with destructors, so they are completely non-existent in Java. The only possible replacement, the finally clause to the try/catch block, requires the programmers who use a class to remember to call resource freeing methods of a class in their finally blocks. Every time. Without fail. Good luck. Java code is needlessly much more verbose for the same task than many other languages. Consider this Java equivalent to the code above:
public void foo() throws Exception {Twelve lines to the first example's five lines. More typing and more opportunities for programmer induced bugs.
ResourceIntensiveClass ric = null;
try {
ric = new ResourceIntensiveClass("have bugs");
ric.initiateResourceLockingStuff();
ric.exceptionRiddledFunction();
} finally {
if (ric != null) {
ric.manuallyCalledCleanupMethod();
}
}
}
When is Java going to grow up and get destructors?
No comments:
Post a Comment