Article 49K4C CodeSOD: Conditionally Exceptional

CodeSOD: Conditionally Exceptional

by
Remy Porter
from The Daily WTF on (#49K4C)

The beauty of structured exception handling is that it removes explicit conditional logic from your code. The conditions are still there, of course: a catch statement is essentially saying "if the exception type is X, then do this". But the strict syntax gives the compiler some freedom, and if you're using a language like Java, which favors checked exceptions (where methods declare what kinds of exceptions they might throw), there are all sorts of shortcuts the compiler might take to keep that efficient.

But hey, that's all implicit, and if there's one thing we've learned, "explicit is better than implicit". How can we make exception handling explicit? Well, our Anonymous submitter inherited some Java code which does just that.

Object obj = null;try { obj = methodThatCanThrowVariousExceptions();} catch (Exception e) { if (e instanceof ExceptionOne ) { //Code removed for anonymity } else if (e instanceof ExceptionTwo ) { //Code removed for anonymity } else if (e instanceof ExceptionThree ) { //Code removed for anonymity } } else { //Code removed for anonymity }}return obj;

While this is pretty heavily anonymized, the highlights are pretty clear. Our methodThatCanThrowVariousExceptions passes its return to an Object. No specific kind of object, of course, just, y'know, a thing. A whatever. If we get a whatever, we return it, whatever it may be. Otherwise, we check each possible kind of exception" in an if. Because why use the basic syntax of a try/catch when you have an if instead?

While this code favors an explicit approach versus an implicit one, I'll leave the explicit language to describe it as implicit in this case.

otter-icon.png [Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today! TheDailyWtf?d=yIl2AUoC8zAaV-C3um9JfI
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments