Wednesday, June 23, 2004

To except(ion) or not to accept
The usage of checked exceptions in Java has been one of the debatable concepts recently and IMHO it makes sense . seeing the misuse of the exception handling , i can understand the issue about it.

For those who came in late, the big debate is the misuse of the checked exceptions in that the programmers can circumvent the exceptions by either swallowing it or still worse throw an RuntimeException or a subclass of it.
Both the approaches violate the principle of checked exceptions that the user needs to know that there is a risk of something going wrong in the program and hence declare it "throws". The errors (RuntimeException ) on the other hand signify that these are not to be handled and are a result of abnormal conditions and for errors it is not required that the user declare "throws" clause

Also the checked exceptions should be caught and re-thrown at different levels to avoid the coupling of the tiers . Assuming that the EJBTier throws an exception indicating that one of the subsystem failure, this exception has to be caught in the Web tier and an different exception needs to thrown wrapping in it the other exception .The J2SE 1.4 provides an way to wrap the reason in it by providing an constructor which takes in a Throwable object and also an method initcause which takes Throwable as an argument. Using either of the above , one can wrap an exception and throw it doing so will require minimal changes only to the web tier in case the ejb tier changes and no changes to the classes which call the web tier.

On the flip side the code for exception handling becomes more bulkier in that u have a nested of catch blocks trying to catch the exception.

One more way to do this might be to have some constants within the checked exception describing about the errorcodes majorCode and minorCode, major code indicating the severity of the exception as business error or system error ,the minor code would indicate the nature of the exception say "Login failure " or "Dup primary key exists" this approach is for u if u dont mind writing catch block and doing a li'l bit of parsing ... By using this approach the users of this program mainly have to just check the code and act accordingly and a single exception could suffice

see Bruce Eckel's suggestions here

No comments: