How can I execute cleanup code regardless of exceptions occuring in my method?

Andre van Dalen

When you put method cleanup code into the finally block of a try clause this code will be executed when your code runs normally but also when an exception occurs in the try block.

As a result of this you do not have to catch and throw an exception just to have your method cleanup code executed, which saves having to put the code in your method twice.

The following example illustrates the finally block used for matching trace logging:

public Result doSomething(Hastable input) 
    throws RemoteException 
    long    millis = 0;
    Result    result = null;

    if (Trace.DEBUGGING) 
        millis = System.currentTimeMillis();
        Trace.log(Trace.DIAGNOSTIC, "MyClass.doSomething: {");
        // get my result for me
        result = doSomethingDangerous(input);
        if (Trace.DEBUGGING)
            Trace.log(Trace.DIAGNOSTIC, "MyClass.doSomething: } msec " 
		      + (System.currentTimeMillis() - millis));
    return result;
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.