Saturday, December 1, 2007

On Handling Errors


I don't like to create accounts just to leave comments in other people's blogs, so I answer them here. The Catty Critic asks about error handling when writing code, and the rule (my rule, the rule, same thing) is surprisingly simple (and probably unoriginal by now):

Don't attempt to handle errors you don't know how to handle. You'll only mess things up.

Her specific question is about a subroutine that was passed a value it wasn't prepared to handle. The only correct way to handle this error is to write code that patches the caller code to make sure it doesn't happen again. This being next to impossible, the next best thing is to alert the programmer to fix it - by crashing or some other spectacular failure.

Let me repeat: handle only errors that you expect and know what to do with. Don't pretend you know what to do with every little thing that may potentially go wrong. Because that's my opinion.