Jul 31, 2004

Exceptions Need Descriptions Too...

In the last few months, I have used the java.util.Map several times without a hitch. Today, I went to use it in a seemingly easy program. The code in question looks as follows, and adds a java.net.URL key item to a String:

// Create a map
java.util.Map map = new java.util.TreeMap();

// Add an item; this is OK.
java.net.URL url = new java.net.URL( "https://www.eyt.ca" );
map.put( url, "A description" );

// This will throw an exception
String description = (String) map.get( url );

To my surprise, I got the following exception on running it:

  at java.util.TreeMap.compare(TreeMap.java:1085)
  at java.util.TreeMap.getEntry(TreeMap.java:345)
  at java.util.TreeMap.get(TreeMap.java:264)
  at ca.eyt.tests.MapExample.main(MapExample.java:31)

Not exactly what I call descriptive. Looking at the above exception, it is not clear what is being cast and why. So I Googled and fortunately, someone else had the same problem. If you read the fine print of java.util.TreeMap, you will note that the key must implement the Comparable interface.

Fine. I have no problem with that, but why could it not just say it? Why did it not do this test when I first put the item into the Map? Why can't the java.util.TreeMap section that casts the object be implemented something like:

Comparable c = null;
try {
  c = (Comparable) key;
} catch ( ClassCastException cce ) {
  ClassCastException ce = new ClassCastException( "Failed to cast the key to the Comparable interface." );
  ce.initCause( cce );
  throw ce;

If so written, it is clear what the problem is, and I do not have to search over what the problem is, or for that matter, talk about it here.

While I suppose that J2SE 5 (or J2SE 1.5 or Tiger) resolves this partially because of its generics support, my point is more general than this particular instance. When you write an exception, put some important information in there. In this particular case, assuming that the Developer did any level of testing of their application, the only person that would see the above exception would be the Developer, so make it a bit more verbose for us. The exceptions that the user sees are a little bit of another story, but with the words chosen properly, everyone benefits.

Speaking of Java's Generics, the August 2004 issue of The C/C++ Users Journal has an interesting article by Vladimir Batov entitled “Java Generics And C++ Templates: Different Approaches to Generic Programming”. The article compares Java and C++'s generic programs, and comes to a conclusion that I totally agree with: Java's generic support helps the type safety of the language, however, it is not really generic programming.

Filed In