Smooth CoffeeScript

Page 83

Error Handling Writing programs that work when everything goes as expected is a good start. Making your programs behave properly when encountering unexpected conditions is where it really gets challenging. The problematic situations that a program can encounter fall into two categories: Programmer mistakes and genuine problems. If someone forgets to pass a required argument to a function, that is an example of the first kind of problem. On the other hand, if a program asks the user to enter a name and it gets back an empty string, that is something the programmer can not prevent. In general, one deals with programmer errors by finding and fixing them, and with genuine errors by having the code check for them and perform some suitable action to remedy them (for example, asking for the name again), or at least fail in a well-defined and clean way.

◦•◦ It is important to decide into which of these categories a certain problem falls. For example, consider our old power function: power = (base, exponent) -> result = 1 for count in [0..exponent] result *= base result

When some geek tries to call power 'Rabbit', 4, that is quite obviously a programmer error, but how about power 9, 0.5? The function can not handle fractional exponents, but, mathematically speaking, raising a number to the ½ power is perfectly reasonable (Math.pow can handle it). In situations where it is not entirely clear what kind of input a function accepts, it is often a good idea to explicitly state the kind of arguments that are acceptable in a comment.

◦•◦

82


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.