Almost every program you will ever write will have errors.
As soon as we started programming, we found out to our surprise that it wasn’t as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.
Syntax errors are probably the most common errors in programming. Luckily they are usually also the easiest to fix. Most languages will point out syntax errors as soon as you try to run or compile your program. Usually you will be provided with a file and line number of the offending syntax. Some IDEs check your syntax as you type, providing a sort of spell checker for syntax.
def add(x, y) return x + y
File "./test.py", line 2 def add(x, y) ^ SyntaxError: invalid syntax
(define add(x y) (+ x y))
Error: during expansion of (define ...) - in `define' - too many arguments: (define add (x y) (+ x y)) Call history: <syntax> (define add (x y) (+ x y))
Type errors occur when your code tries to do things like adding an integer and a string together. Depending on the language you use you may be notified of type errors when compiling your program or while your program is running. Type errors are also very common and are a little bit harder to fix.
def add(x, y): return x + y add(1, "a")
Traceback (most recent call last): File "./test.py", line 4, in <module> add(1, "a") File "./test.py", line 3, in add return x + y TypeError: unsupported operand type(s) for +: 'int' and 'str'
(+ 1 "a")
Error: (+) bad argument type: "a" Call history: <syntax> (+ 1 "a") <eval> (+ 1 "a") <--
Logical errors occur when you write code that performs correctly, but does not give the output that you desire. Logical errors can be the worst kind of bugs. There is rarely any support for detecting them built into the language, as there is technically nothing wrong with the code. These bugs happen somewhat frequently and can range from minor inconvenience to major disruption.
Below is an example of a logical error that would fall into the minor inconvenience category. We’re trying to define a function named add that takes two arguments, adds them together and returns the result. The code we have below does not have any syntax or type errors in it and it is perfectly valid code. However instead of adding the two arguments it subtracts them and we get the answer 0 when we expected the answer to be 4.
def add(x, y): return x - y add(2, 2) #>>> 4
(define (add x y) (- x y)) (add 2 2) ;>>> 4
Errors and Error Handling
Each language will have its own way of representing errors. Some languages provide a mechanism called error handling which let’s you control what happens when an error occurs. We’ll get deeper into errors and error handling in an upcoming WITH article.