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.

Tuesday, May 10, 2005

One more Java web tier?

A new web tier has been sprung from the Spring camp called Spring Web Flow. At first, I was a bit wary of yet another web flow - after your typical JSP/Servlets, Struts, WebWorks, and now this.

But one thing surprised me though - the simplicity of the architecture. The intereseting aspect is that they are equating the page flow of a website as a state diagram. So, in effect, a website (or more specifically, a specific flow of web pages to accomplish something) is like the state diagram of a class. Each state is represented by a page and each event is an action that is performed by the user.

It's so simple that it drives me crazy why I didn't think about it when I read about the GoF state pattern!

With a nice architecture, I hope it keeps its promise. I'm thinking if I should use it in my Carnatic Search Engine.