Fwd: Re: [jdom-interest] NoSuch*Exceptions in JDOM

Brian brian at qcorps.com
Tue Jun 27 15:27:38 PDT 2000


The benefit of returning null is that it's a real pain to deal with 
exceptions in the common case (at least for me) when you want to do 
something if an attribute is present, and something else if it isn't. 
Compare these two snippets:

// returning null
String value = element.getAttributeValue("foo");
if (value!=null) {
  // something
}
else {
  // something else
}

vs.

// throwing exception
String value=null; 
try {
  value = element.getAttributeValue("foo");
}
catch(NoSuchAttributeException ex) {}
if (value!=null) {
  // something
}
else {
  // something else
}

IMHO, the first is much easier to understand. As another poster pointed 
out a while back, exceptions are intended to be used for actual errors 
(e.g. trying to open a file that doesn't exist), and not finding an 
attribute or child is not always an error. As a compromise, I would be ok 
with hasChild() and hasAttribute() methods, then you could do:

String value = null;
if (element.hasAttribute("foo")) {
  value = element.getAttributeValue("foo");
  // something
}
else {
  // something else
}

which is an improvement. Just my opinion...

Brian


>What would be the proposed benefit for returning a
>null value rather than an exception?
>
>Exceptions can sometimes allow you more flexibility
>when handling things... for example.. if the child
>that wasn't found WAS the entire HTML document, you
>could abort the rest of the process and/or start over,
>rather than proceed with a value that is null or
>set...



More information about the jdom-interest mailing list