Friday, May 23, 2008

The bane of java exceptional handling

Exception handling should be fail safe. What it implies is that the last exception which is thrown should be propagated up the call stack. However taking a look at a simple example shows how complicated exceptional handling can be.
Lets take a scenario of the following block of code where we are trying to open a file
InputStream input = null;

try{

input = new FileInputStream("myFile.txt");

//do something with the stream

} catch(IOException e){
throw new WrapperException(e);
} finally {
try{
input.close();
} catch(IOException e){
throw new WrapperException(e);
}
}

Now suppose that the file myFile.txt does not exist, so an FNFE(FileNotFoundException) would be
thrown from the try block. The catch blocked would catch the FNFE , wrap the exception and rethrow it.
Till now all seems well. When the call reaches the finally block, since input is null,
a call to input.close() would result in a NullPointerException(NPE) being thrown.
Now since the finally block never catches a NPE, it would propagate up the call stack.
The WrappedException(WE) from the catch block simply disappears.

The way to avoid this would be to check whether the resource in not null in the finally block.Right, makes
complete sense, but lets take another scenario. Lets say the file myFile.txt is found but there is an
IOException(IOE) thrown due to some other reason. What happens, the try block throws IOE, which is
wrapped and rethrown. Now before the exception propagates up the call stack, the finally block is executed,
if the call to input.close() fails, a new IOE would be thrown, but the original exception would still be lost.
Damn Cute, aint it.


The emperor and me beaching

The Devil next door

Kaiser The Emperor