James Gosling talks to artima.com about exceptions and how they’re used in the real world.
The discussion about the “one true path” strike a chord with me. I spend several years working on a networked medical application. When you’re talking to a network then anything can happen. The network goes silent. You get the wrong kind of packet. The network layer gives an error. You receive a data packet containing bad data (like, “length of next data item = 0xffffffff bytes”). The machine you’re talking to rudely drops the connection rather than terminating gracefully. These aren’t theoretical problems — they occur regularly in the field. And if you don’t handle each and every one of them correctly, you’ll get annoyed customer phoning you up and you spend your weekend fixing bugs instead of having fun.
And if you think you’re safe because you’re not talking to a network, how does your application cope when the users disk gets full? Every single write to a file can potentially fail.
So, I think the whole notion of the “one true path” is a seductive fallacy. It’s seductive becuase the “one true path” is where all the cool stuff happens. Coders love making computers do cool stuff. In constrast, handling all the exceptions and return values is dull – it’s is a bit like “dotting the i’s and crossing the t’s”. Who cares if your application bombs when the user’s disk is full? Well, the user sure will.
But when you are a grown-up programmer then you don’t get to just do the cool stuff. All of those “error conditions” are first-class code routes, just like the “one true path” and some day Real Soon Now a customer is going to run down one of them.
Here’s a fun idea: Before you ship your next product, run your test plan on an instrumented build and record code coverage information. Then in your shipped product, detect when an end-user starts running down a codepath which wasn’t touched by your testing and then pop up a big alert box saying “Warning: You are the first person to ever run this bit of code!!”. I’d love to hear of a company which dares to do this.