Nov 26

Error-Checking Strategies

Filed under: Development | Taged as: , | Comments Off

Error handling is one of programmings most important issues. It makes your programm stable and prevents it from an inconsistant state. Error checking and handling always boosts your lines of code. So if it has to be this was, how might a convenient strategy for this look like?

One possible solution is the so called “look before you leap” (LBYL) strategy which means you have to check in advance before attempting an operation to make it valid. This approach might look like this:

def justdoit(x, y):
if y == 0:
print \"division by zero\"
else:
return x / y

Well, if you look at it, this code has some obvious drawbacks:

  • the checks diminish the readability and clarity
  • there is more work needed for checking then for the main part of the programm
  • if the operation changes, all checks must be reviewed

Most modern programming languages support exceptions. Their use leads to another strategy which is called “it’s easier to ask forgiveness than permission” (EAFP). This approach avoids the defects of LBYL:

def justdoit(x, y):
try:
return x / y
except ZeroDivisionError:
print "division by zero"
return None

EAFP is most often the preferable error-checking strategy an comes to it’s full potential when coming up with nested function calls where errors bubble up if not catched.

In large programms your try/except statements can become too wide if you want to catch all errors and anomalies that might arise. To avoid this, keep your try-statements small making only the necessary calls.

Comments are closed.