Thursday, May 19, 2011

Error Handling - An exercise for the reader....

So many times I read through books about programming, and the examples always skipped nicely over error handling. It was left as "an exercise for the reader"....

Even in college, error handling was a poor relative to algorithms, data structures, methodologies and such.

Of course in the real world, things go wrong all the time.

  • Opps, the file system is read only, someone set up the permissions wrong on the share.
  • Database connection, ah, well you see we had to restart the database.
  • Config files, "I only changed one setting" and so on.

I can't tell you how to handle errors, because, as always, that depends. Rather, I can offer some thoughts.

When a program goes wrong, you need to be able to figure out where and why it went wrong. That is hugely important. A failure that neatly tells you what is wrong, in such a way as you can sort it out is almost friendly.
A program which locks or crashes without giving you the slightest clue as to what is going on (or not going on for that matter) may cause all manner unkind thoughts.

It's nice too if your program can survive the little problems. If a file is read only, and you cannot save your data, then crashing out is a little rude, allowing the user to save somewhere else is more polite.

A whole pile of your error will go toward these two straight forward goals. And then you are back to the other requirements of consistency, simplicity, and not having 50% of your code taken up with dealing with errors. But now that you have goals, you can plan for the bigger picture. Too often in my early days, I wrote a whole pile of error handling code without really considering quite where I was going. Classic can't see the Wood for the Trees stuff.

Some things to consider:
  • Don't log errors that are not errors. When something real happens and I'm looking through the log file, if I have to try to figure out the "errors" that happen all the time from the real errors, I may not feel much love for you.
  • Exceptions are expensive, throw them for exceptional events. Don't make them part of the normal control of you program.
  • When you log an error, log as much as you can, and log it consistently. Allow for the fact that you might want to process logs files automatically. Comma Separated Fields are your friend here. Grep then Cut and Paste into a spread sheet, and off you go.
  • Consider third party logging tools eg log4net
  • Log "interesting" things as information, so that you know that X happened just before the crash. You can't trust users to remember exactly what they were doing, they were busy just before things went west.
This just touches on some of the ideas that shape the bigger picture. You may have other considerations too.

No comments:

Post a Comment