Women in Technology

Hear us Roar



Article:
  Best Practices for Exception Handling
Subject:   Thanks for a most excellent article!
Date:   2003-11-28 12:49:09
From:   dashmore
It takes courage to challenge one of the worst and most pervasive beliefs in the Java world: that all exceptions developers write should be checked exceptions. This is a subject, like religion or politics, that people hold very strong, but not always very informed, beliefs.


I agree with the vast majority of your article. The only point I would challenge you on is your assertion that high-level exceptions shouldn’t be caught. This point could have been supported a little more.


Your article concentrates on what exceptions to *throw*. The question of “what” exceptions should be *caught* and “where” are equally complex topics.


In deciding “what” exceptions to catch, the key question is: will the exception type caught cause me to process the error any differently? If the answer is yes (e.g. SQLExceptions where a rollback() can be issued), then you should catch the specific exception. For all others, the most common action is to record the exception and context so that a developer can fix the problem. For these cases, there’s no benefit to catching the specific exceptions as the code in the catch blocks would be largely identical. Catching a high-level exceptions greatly consolidate code.


I, in fact, when catching high-level exceptions, recommend that you catch *Throwable* as catching *Exception* misses far too much. However, making that claim would have gotten you more hate mail.


Exceptions should be “caught” where an alternative action can be taken (e.g. rollback issues for a database transaction) or if meaningful information can be recorded that would enable a developer to more easily diagnose and fix the problem. Typically, the most common place to record context is the entry point for the application action. With web applications, this is typically in the servlet, web services, and/or enterprise beans.


Thanks, again, for an excellent article. I wish you the best of luck in future work.


Derek C. Ashmore (dashmore@dvt.com)
Author of “Streamline your Exception Processing” (http://www.ftponline.com/javapro/2003_05/magazine/features/dashmore/)