The Daily WTF
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
To read the full article click on the 'post' link at the top.