ix.util
Class WithCleanup

java.lang.Object
  extended by ix.util.WithCleanup
All Implemented Interfaces:
java.lang.Runnable

public abstract class WithCleanup
extends java.lang.Object
implements java.lang.Runnable

A class that encapsulates the tricks needed to use a "finally" clause that might throw an exception. A throw (or return) out of a "finally" clause will cause any exception from the "try" clause to be lost. So there has to be another try-catch inside the "finally", and up to two exceptions might have to be handled.

Instead of creating a plain Runnable, like this:

     new Runnable() {
         public void run() {
             ... do something ...
         }
     }
 
you can instead create a WithCleanup:
     new WithCleanup() {
         public void body() {
             ... do something ...
         }
         public void cleanup() {
             ... do some cleanup ...
         }
     }
 

When the WithCleanup's run() method is called, it will call body() inside a "try", and cleanup() inside the corresponding "finally".

If any exception (any Throwable) is thrown out of the body or cleanup, this method throws a RethrownException. If only the body, or only the cleanup, throws an exception, then the RethrownException is a simple wrapper around that exception. If both body and cleanup throw an exception, the RethrownException is wrapped around the body's exception, but its message describes both exceptions. In addition, Debug.describeException(Throwable) is called on cleanup's exception to print its backtrace.


Constructor Summary
WithCleanup()
           
 
Method Summary
abstract  void body()
          The main part of what this object should do when its run() method is called.
abstract  void cleanup()
          Whatever this object should always do after its body() method has returned.
 void run()
          Calls body() in a "try", cleanup() in the corresponding "finally", and ensures that any exception thrown by body() is rethrown.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

WithCleanup

public WithCleanup()
Method Detail

run

public void run()
Calls body() in a "try", cleanup() in the corresponding "finally", and ensures that any exception thrown by body() is rethrown. See the class's javadoc for a more complete explanation.

Subclasses should not normally redefine this method.

Specified by:
run in interface java.lang.Runnable

body

public abstract void body()
                   throws java.lang.Exception
The main part of what this object should do when its run() method is called.

Throws:
java.lang.Exception

cleanup

public abstract void cleanup()
                      throws java.lang.Exception
Whatever this object should always do after its body() method has returned. cleanup() is called in a "finally" that goes with a "try"-"catch" that's around the call to body().

Throws:
java.lang.Exception