Search This Blog

Saturday, January 27, 2007

Java Exceptions

Last week, I had an interesting discussion with Sachi, Greg, Seshu and Muthu regarding exceptions. I had used an exception in my code to handle application level error conditions like so:

public void doStuff() throws AppExcecption {
// Some code
if(error) {
throw new AppException("Cannot handle this automatically.", errorCode);
}
}

and somewhere else

public void controller() {
try {
Data d = doSuff();
writeData(d);
} catch (AppException e) {
writeErrorCode();
}
}

Sachi's contention here was that I should not use exceptions unless I have an exceptional case. My initial argument was that an application error was indeed an exceptional case as far as the application is concerned and hence, it's perfectly fine to throw an exception.

He was arguing for something like this:

public ErrorCode doStuff(Data d) {
// Some code
if(error) {
return errorCode;
}

return null;
}


and elsewhere

public void controller() {
ErrorCode code = doStuff(d);
if(code == null) {
writeData(d);
} else {
writeError(code);
}
}

So, finally I decided to try his approach and found that it was also equally readable, and in fact, made me do some refactorings that made the code clearer.

While I still argue that in some cases throwing an exception like I mentioned is valid, I have softened up a bit. Here's my final thought:

1. Do not throw exceptions.
2. If you have to throw exceptions, try handling them as soon as possible.
3. If you cannot handle them right away, throw them to the caller.

The steps above have also been mentioned in the Robust Java - Stelting book.