Modern programming languages have some method of handling errors when they happen. The term handling means having a code path to follow when the error occurs, for instance it might mean simply displaying that an error has occured or it might have a different solution to the problem.
JavaScript has the try
and the catch
keywords
to handle errors. This is shown in the next code sample:
var list = [30, 40, 50]; try { alert(list[1]); //Undefined listf, so getting an array index will not work alert(listf[1]); } catch(e){ alert(e); }
Why errors happen
JavaScript is a language that is compiled and immediately interpreted. This means that it is not checked until compile time. When this is the case, if a program has a typing error or a value that is not within the normal bounds the program will stop executing.
In a language such as C, Java or VB.NET an error could be identified at compile time. This is, understandably, called a compile time error. An error that occurs when the program is running is called a runtime error. In a language such as Java, a compile time error will cause the program to stop compiling.
In JavaScript, both compile and runtime errors can be handled by a try-catch statement.
Try-catch
The previous example demonstrated an error being captured. This works by attempting (or trying) to
run the code within the try
block. If this fails, the error
is a handled (caught) and the catch
block is
executed.
Most programming language support passing the error to the catch
block. In the previous example, the error is passed to a variable e
.
Producing errors
Most programming languages also offer a method to create an error. This is called throwing
an error. In JavaScript, the throw
keyword is used to
throw an error:
throw "Error occured!"; alert("Reached");
In the previous example, because an error occured or at least an error was thrown, the alert could not be reached.