In this post, we are going to look at errors and exceptions in JavaScript. Errors and bugs will happen even to the most careful programmer. They mainly happen due to a direct error that the programmer makes or because the program does something that wasn’t accounted for. luckily, JavaScript features some in-code tools to help us debug these problems.

Try-Catch Statements

The main in-code method that JavaScript has to handle errors is called a try-catch statement. The try-catch statement is a type of control flow statement in which the catch block will only execute if an error is thrown in the try block. In other words, the try block is where the code we want to test resides. The catch block is a block of code which will be executed if the try block throws an exception.

Here we have a pseudo-code version of a try catch block. The try block throws an error, e which is passed into the catch block like a variable. We can pass a variable into catch because when JavaScript code raises an exception it generates a message. We can use the throw statement to manually throw our own exceptions in JavaScript. The throw statement can take a type of String, Number, Boolean or Object.

The main reason why the try-catch statement is so powerful is because it is hard to tell what a user will do when they are accessing your program. One of the more common uses for a try-catch block is for form validation. You can’t control what a user will put into your input text boxes but you can restrict what inputs are valid in these boxes.

Using Debuggers in JavaScript

errorThe other main resource used for dealing with bugs in JavaScript is a debugger. The debugger allows you to set breakpoints in your JavaScript code to see what “state” the code is in at a given moment. Natively in JavaScript, there is a keyword debugger which will stop the execution of the code and send a call to a debugging function. This is basically like setting a breakpoint in the browser, except you manually are typing it into your code. If you try typing debugger into your JavaScript console, it should bring up your browser’s native debugger window.

In most browsers, your debug window is actually your JavaScript console or an extension of the JavaScript console. It is actually quite common for programmers to use the console.log() function for debugging as well. You may notice that upon opening the console in certain URLs you will see error codes. These are mostly from broken JavaScript on the page you are viewing or from an extension you have installed on your browser.

Closing

Though this post was much shorter than normal, we covered error exceptions in JavaScript and exception handling in JavaScript. We looked at the throw statement, the try-catch statement and we looked at the debugger keyword. We also talked about setting breakpoints and looking at state.

In our next post, we will start to look at a simple real world example of JavaScript.