Errors & exceptions 14 Oct, 2003
OK, so I know I'm a newbie at this object oriented thang, but I remember when I first learned about exceptions in Java, and how they work. As someone who was getting pretty tired of
On Error Goto lblErrs…, it struck a chord let me tell you! Why clutter your code with error handlers and logic based on what error is thrown? The concept in Java, that exceptions are instances of / sub-classes of the core
java.lang.Exception class makes real sense. De-couple your error handling from your code! Yes!
For me this works, I like it. I nodded all the way through Ned's article Exceptions vs. status returns even though I don't have the programming legacy he has (i.e. dealing with status returns in C or C++).
I was amazed therefore to see Joel Spolsky's article, Exceptions, in which he promotes the use of status returns in one's code, rather than exceptions. Indeed, he likens throwing and handling exceptions to the dark old days of "Goto". Which is kind of strong… ;-):
The reasoning is that I consider exceptions to be no better than "goto's", considered harmful since the 1960s, in that they create an abrupt jump from one point of code to another. In fact they are significantly worse than goto's:
- They are invisible in the source code. Looking at a block of code, including functions which may or may not throw exceptions, there is no way to see which exceptions might be thrown and from where. This means that even careful code inspection doesn't reveal potential bugs.
- They create too many possible exit points for a function. To write correct code, you really have to think about every possible code path through your function. Every time you call a function that can raise an exception and don't catch it on the spot, you create opportunities for surprise bugs caused by functions that terminated abruptly, leaving data in an inconsistent state, or other code paths that you didn't think about.
With regards point one: yes, exception handling (not the exception itself) is indeed invisible to your code. That's the point innit? Now to point two: in Java, if I code something that could go wrong, my LS background tends to kick in I must admit. I find myself performing basic tests or asserts with regards an object or variable's state, before continuing with my code. My bad? Perhaps. But for stuff that can throw an exception, I wrap it in a
try… catch block. Isn't that what they're there for? I am somewhat bemused.