CodeSOD: Catch By Yourself
We've all seen the empty catch block, the "swallow errors and ignore them". David sends us a "superior" example of that anti-pattern, with several bonuses to make it even more of a WTF.
/** * Insert the method's description here. * @param bean java.lang.Object * @param bean_template java.lang.StringBuffer * @param bufXML java.lang.StringBuffer */protected static void appendBeanTemplate(Object bean, StringBuffer bufXML) { int iEndTag; StringBuffer xmlTemplate = new StringBuffer(); try { iEndTag = bufXML.toString().lastIndexOf("</" + getClassName(bean) + ">"); writeChildBeanDescription(bean, xmlTemplate); bufXML.insert(iEndTag, xmlTemplate.toString()); } catch (Exception e) { try { throw new Exception("Error creating xml bean description."); } catch (Exception ex) { } } }
Taking it from the top, we start with an incomplete JavaDoc comment. "Insert the method's description here". Then we accept a parameter called bufXML, but it's a StringBuffer, not an actual XML object, which sets us up for the ugly, hideous, "please don't" string mangling approach to interacting with the XML. The class name of the bean object is used to as a tag, we track the last index of that tag, and then insert some more stringly-generated XML into that position.
Everything about that is bad and terrible. Working with XML isn't nice, but using the actual XML classes in Java makes it easier and safer. I guess we can say, "at least it's not regexes".
But the real star of the show is the exception handling. We catch any exceptions this string mangling generates. Then we try... to throw a new exception. Which we catch, only to do nothing with. This code is like a lonely child on the playground, throwing a ball up in the air and catching it themselves because no one else will play with them.
It'd be sad, if it weren't so awful.
[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!