JavaScript Error Handling

Error handling is a very important topic, not only in JavaScript but also in development in general. Let’s face it. Even if you write the most perfect code, once you put your code outside of the local environment to users to use, chances are, your code will fail eventually. Your code can fail due to numerous reasons, for example, user can enter some erroneous data or they can have networking issues. When this happens, it is important to show the user informative and appropriate error message. Otherwise, you may cause frustration on the user end, which is something that either the programmer nor the user want. So let’s take a look at the example of how we can handle errors in JavaScript.

As you can see at the code above, we have a function with three blocks. These blocks are trying, catch and finally. In the try block, we put the code that we want to execute. If an error occurs in this block, an exception will be thrown. This exception will be caught with the catch block. Execution of any additional script in try block will be canceled. The only blocks that will be executed after the exception is thrown, will be catch and finally blocks. Catch block usually holds error reporting code and instructions on how to proceed when an exception has been thrown. The error message can be displayed by the message variable.

Final block represents a part of the code that will always be executed. If your code does not throw an error or if it does, finally block will get executed. The purpose of the final block is not immediately apparent. The best example to explain when to use it would be this. Let’s say we have a global variable. In the try block, we initialize the variable and when we process it, it needs to be reset to an undefined value. Now imagine that you would initialize that variable and your code would break. This is where you would use finally block. The global variable will get set to undefined in successful and unsuccessful script execution in finally block.

Obviously, there is no need to put try catch blocks all over your code. If something is really simple like var x=1+1; then you would not need to put this into a try-catch block. Try catch block use cases would be when you are dealing with user input, where you cannot expect from user to always enter valid data. Another example of where to use it would be if you have two functions. One returns an array and the other uses that array to iterate over it. If by any chance, your code would break in the first function, your next function would certainly crash your script execution. Here you would definitely need to use an error handling functionality in terms of a try-catch block.