Friday 2 July 2010

Error checking should be a first class citizen.

I don't think that error checking gets the attention it deserves. It should be one of the very first things that you learn to do properly when your developing in a new language and yet documentation on doing it "properly" is thin on the ground. Good error checking is fundamental to good code, but what's considered good changes depending on what your doing and in what language.

Python, for example, has very good exception checking; but do you use exception check all the time or do explicit checks for known errors? Well after some digging around the Python glossary states:
EAFP: Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
So exception checking is considered a common style in Python, and further checks turn up this blog on the performance on Python's exception checking. After my own checks is seems that the exception block adds only a very minimal amount of overhead to the execution speed. The overhead from a try block is likely to be less than anything other than the most cursory explicit checks and you can error check a loop with a single try, whereas explicit check would have to be called per iteration. On the down side, if an exception in thrown, it's expensive. A good rule of thumb would be to use exception checking when code is unlikely to fail and explicit checks where it is.

Javascript is another language that supports exception checking, however there have been many articles indicating that using it can (under certain circumstances) severely impact performance-critical areas of code and should be avoided. In addition unlike most languages Javascript does not raise an error when trying to access an invalid property (it returns 'undefined') so this type of error would not be caught by a try block anyway. Finally Javascript errors do not cause a unilateral exit, it only stop the execution of of the current function and attempts to continue. This can of course cause cascading errors, but more importantly can lead to a more robust program if it designed to suit this style.

These are just some quick examples, and doesn't begin to cover things like custom exception re-raising, but it took a surprising amount of reading to find out these few scant details. Shouldn't these discussions be formalised right after basic syntax in the manual?