Article 6AAWX CodeSOD: Exceptional Messages

CodeSOD: Exceptional Messages

by
Remy Porter
from The Daily WTF on (#6AAWX)

Structured exception handling is an excellent way to handle errors, but wouldn't it be nice if you could execute a different branch of code depending on what specific error just happened? It's a pity that there's just no possible way to filter exceptions using the good old fashioned try and catch. Fortunately, Mateusz has a co-worker who invented that wheel for us.

if (something_bad_happens) throw new Exception("File is not correct; 88888");if (something_else_happens) throw new Exception("Tag len exceeded; 1337"); ...catch (Exception ex){ if (ex.Message.Contains("88888")) { ... } else if (ex.Message.Contains("1337")) { ... } }

Here, we include a numerical error code in the exception message, which means we can handle the exception by simply doing a Contains check for that numeric code. It's beautifully simple, the easiest possible way imaginable to handle exceptions, or at least the easiest way if you don't understand how to properly write a catch block.

Obviously, the correct version of this code would throw exceptions of differing types, and then catch (IncorrectFileException ex), and catch(TagLenExceededException ex), as appropriate. But at least we have a more fragile, harder to read, and runtime checked exception handler, instead of the regular exception handling approach.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
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