i find myself tasked with creating my team’s exception handling strategy.
in doing some research, i’ve had one of those “you mean i’ve been doing it wrong all these years?” type epiphanies.
i’ve always been the sort who writes the most rock solid, fault tolerant code i can. i check parameters obsessively, even in private methods. i make business owners crazy with my questions of “what if this obscure possible event happens” (and then they thank me when it does, thankyewverymuch, or are surprised when someone else’s code didn’t predict the future the way mine always seemed to.).
most of the other developers on my team come from the other side - if it compiles and works the first time, it’s fine until it breaks. both approaches have their cons. their code breaks more than mine. but they get stuff “done” a lot faster. i’ll let you guess who management likes better.
in the process of moving from the procedural world to object oriented program, i discovered try-catch-finally and exception handling, i was put under the impression that one should discover all possible exceptions, catch them all, and when all else fails, catch the general exception and do something with it. and heaven forfend that i actually intentionally throw an exception! that’s madness!
well, i may be changing my mind.
for context, i’ve been sucked into Microsoft.NET Framework programming. and for all my wailing and gnashing of teeth, it’s not all that intolerably horrible. of course, i was stuck in Java before this, so drawn your own conclusions. oh, what, you guessed that from my obsessive attitude towards catching exceptions?
anyway, i stumbled upon Jeffrey Richter’s Applied Microsoft .NET Framework Programming, where he makes the point, “After all, an exception is simply a violation of a programming interface’s assumptions.”
which made me realize how often i’ve bent over backwards to handle situations where, for example, i just want a simple method to return true or false…but i may need to know if something failed. but i’m not allowed to throw an exception, because that’s BAD. so i just return false. and then later i spend forever stepping through code with the debugger trying to figure out where something’s failing, only to discover that it’s because some piece of data 15 layers deep isn’t properly associated with another one, and the method that needs to know is hiding that from me by quietly returning “FALSE” when really it should say “HEY THE DATA IS BORKED!” since the vast majority of what i do is getting data from a database and deciding what to do with it, this happens a lot.
so now i finally realize the power of exceptions. i will throw exceptions whenever it damn well suits me. i will do it with pride. exceptions are my friend!