Darwin's Theories Blog

New Theories for a New Time

A Pox Upon all of your getMessage() calls

2009-01-19
Rant at fellow Java developers
If you're not a Java programmer, you might as well run along to the next blog entry below. If you are, how often have you seen - or tolerated - code like this in a library you're using?

try {
     clazz= Class.forName(className);
} catch (ClassNotFoundException e) {
      throw new IllegalStateException(e.getMessage());
}

What's really wrong with this code is that it loses information. The fact that the class requested could not be found is completely obliterated, wasting hours and hours of time amongst all the people who use the API. If the class name is org.foo.Foo, the only message the user gets is:

IllegalStateException: org.foo.Foo

What the user would like to see is something like this:

IllegalStateException: ClassNotFoundException: org.foo.Foo

Unlike the former, that is actually useful, and tells you how to track down the problem. And without having to download, accept licenses on, build a project around, etc., etc. the offending library.

What's even more galling is that all the library maintainer needed to do is write the "throw" line as:

throw new IllegalStateException(e.toString());

You know, the offending version of the code above is only one rung up the latter to hell from code like this:

try {
     // something here
} catch (Exception e) {
}

That is, code that "swallows" an exception. Believe me, in my adventures with numerous web development toolkits, I've seen all of these. And reported them. 

Folks, there's nothing like good error reporting. And this is nothing like good error reporting. Neither, in fact, is any stack trace that the user gets to see, but that's a topic for a later post.
Reply from Lak at 2009-01-19 13:31:44.078

Rather:  pox on the fellow who wrote the ClassNotFoundException class to put out a non-descriptive message completely contravening the getMessage() contract.

After all, the
<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getMessage()">javadoc</a>
for getMessage() reads:

Returns the detail message string of this throwable.


The poor clod who is simply converting the checked exception to a runtime one probably doesn't know that the getMessage() method is so unhelpful.  And if you can't trust the javadoc, what can you trust?

Reply from Anonymous at 2009-07-29 05:36:57.957

It actually does say "detail message" and not "detailed message". To me this sounds like the message only needs to have additional detail(s) about the exception. The name of the class which couldn't be instantiated does count as a "detail", right?

Tags