Monday, September 13, 2004 - Posts

Exceptions == Errors

Recently, someone asked me, "What is your view on Exceptions? Should we or should we not use Exceptions to steer logic flow, and why (not) ?"

My view is that Exceptions are errors. They're the same thing. In my view, an Exception is something that never occurs in a perfect world (i.e. with perfect software running on perfect hardware). In the non-perfect world, a hard disk may fail to write (causing an Exception in the software that is trying to save a file), and software may be buggy because its assumptions are wrong (trying to read from a file that isn't there also causes an Exception). But when, in a soccer game, a player scores a goal, in my view that is not an Exception. Even if such moments are rare or, ahem, exceptional.

Using Exceptions for logic flow == bad

Again, in my view, it is bad to use Exceptions for anything other than managing errors. Code that expects an exception is bad (unless it is unit-testing code). Take the following example (pseudocode-ish):

try {
      myFile = File.OpenText(fileName);
} catch (Exception e) {
      myFile = File.CreateText(fileName);
}
...

I think this is horrible code. This is the hand of a lazy programmer. Try to open a file, and if you get an error, create the file. The following is much better:

if (!File.Exists(fileName)) {
    myFile = File.CreateText(fileName);
} else {
    myFile = File.OpenText(fileName);
}
...

This code is robust: it verifies its assumptions, and if they aren't met, takes appropriate action. Here, if an Exception occurs, it is unexpected.

Exception management is expensive, in the sense that takes more CPU cycles than being proactive as in the example above. I've measured performance differences between implementations that did and did not rely on Exception handling for logic flow, and the ones that did not performed better. That's another reason, although not a silver-bullet one, to view Exceptions strictly as errors.

What's the scientific point of view?

Now, I've spent some time trying to find the "scientific" point of view regarding this matter, but couldn't come up with anything solid in an acceptable timeframe. Is my view on things shared by the academic O-O world or not? What about you?

with 0 Comments