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;


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

//do something with the stream

} catch(IOException e){
throw new WrapperException(e);
} finally {
} 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: