Java News from Thursday, December 4, 2003

The recent XOM Code Coverage results that Brendan Humphreys sent me on Monday have gotten me thinking about no-args constructors in exceptions, mostly because the results demonstrated that I wasn't actually using those constructors. Consider a typical exception subclass:

public class MyException extends Exception {

  public MyException() {
    super(); 
  }

  public MyException(String message) {
    super(message); 
  }

}

Java 1.4 adds one more constructor that takes both a message and a root cause. I've followed this particular pattern so many times I could type it in my sleep. It often shows up in one form or another on my midterm and final exams. But does it really make sense? Why, exactly, do we need the no-args constructor? Certainly it's better to provide a detailed message than not to provide one. Is there any time you should not provide such a message? Certainly this is the case for some of the standard exceptions in java.lang. For example, it would be quite hard to provide a detail message for all occurrences of NullPointerException or OutOfMemoryError. However, for exceptions you define yourself, and which can only be explicitly thrown by a throw statement, is there any time or reason you would not want to provide a detail message?

If there's not, may I suggest the time has come to stop reflexively writing no-args contructors in our exception classes? Eliminating them has a number of advantages:

Is there really anything you can do with a no-args exception constructor you can't do without one?


Picture of a Cat, Tomcat logo The Jakarta Apache Project has released Tomcat 5.0.16, the servlet container for the Apache web server and the official reference implementation of the Java Servlet API and Java Server Pages (JSP). Tomcat 5.0 implements version 2.4 of the Java Servlet API 2.4 and version 2.0 of Java Server Pages. The numbering is a little confusing, but this appears to be the first stable release in the 5.0 series. It should really be numbered 5.0. New features since Tomcat 4.0 include: