2.7 Debugging
Errare humanum est. Making mistakes is part of our day-to-day life and, in general, we know how to deal with them. Unfortunately, this does not apply to programming languages. Any mistake made in a computer program will result in an unexpected behavior.
The process of detecting and correcting errors is called debugging. Different programming languages provide different mechanisms to accomplish such process. As we will see, Julia is particularly well equipped in this domain.
Generally, errors in programs can be classified as syntactic errors or semantic errors.
2.7.1 Syntactic Errors
Syntactic errors occur each time we write code that does not follow the language’s grammar rules. As an example, suppose we wish to define a function to compute the area of a triangle and we write:
> triangle-area(base, height) = base*height/2
ERROR: syntax: "area(base, height)" is not a valid function argument name
The error Julia is warning us about is that the function definition does not follow the required syntax and, in fact, a careful look at it shows that we made a mistake in the name of the function: instead of triangle-area, we should have used triangle_area. This mistake makes it impossible for Julia to recognize the program as a proper function definition and, therefore, Julia reports a syntactic error, i.e., it complains that it found a sentence which does not obey the language syntax.
There are several other types of errors that Julia is capable of detecting; some of these will be discussed further ahead. The important thing to remember is not the different kinds of syntactic errors that Julia is capable of detecting but, rather, Julia’s capability to check the expressions we write and detect syntactic errors in them.
2.7.2 Semantic Errors
Semantic errors are very different from syntactic ones. A semantic error is not the misspelling of a sentence but rather a mistake in its meaning. In other terms, a semantic error occurs when we write a sentence which we think has a certain meaning but, in reality, has a different one.
Generally, semantic errors can only be detected during the evaluation of the expressions that contain them. Some semantic errors are detectable by Julia’s evaluator but many of them can only be detected by the programmer.
As an example, consider a meaningless operation such as the sum of a number with a string:
> 1+"two"
ERROR: MethodError: no method matching +(::Int64, ::String)
As we can see, Julia complains that there is no way for it to add an integer (the type Int64) with a string (the type String). In this example, the mistake is obvious enough for us to detect it immediately. However, with more complex programs, the process of finding mistakes can often be slow and frustrating. It is also a fact that, the more experienced we get at detecting and correcting errors, the faster we will be at doing it.