Getting rid of Errors in JavaScript📌

Getting rid of Errors in JavaScript📌

Introduction

We programmers tend to code a hell lot and in the meanwhile some annoyingly small or sometimes bigger error find its place in the codebase that many a times possess the power of taking the whole system down. So as responsible programmers, it is our duty to write error free code as far as possible. To assist us in our endeavour, programming languages came up with the Error Handling or Exception Handling methodology that make our lives a hell lot easier. As far as I know, every programming language has its own implementation of error handling but we are particularly interested in the JavaScript domain.

See today, JS is being used in almost all platforms, be it mobile, web or desktop. So it is of utmost priority that the code has been error handled to avoid bugs. This blog will take you to the nuances of where to explicitly declare error handling, what kind of errors can occur and how to deal with them.

So let's begin the search...

What actually happens when error occurs?

JavaScript is a single threaded synchronous programming language. In crux, it runs line by line by default. Consider the following program that contains an error and observe carefully🧐.

let firstName = "Raushan";
console.log("first line passed");
console.log(firstName+" "+lastName);
console.log("Checking after error line");

It is clearly observable that the above program is erroneous as it doesn't have any lastName variable that is to console logged in line 3. So what would happen? Let's see:

error.png

If we see at the console area, we observe that error occurred at line 3, as we predicted. So it threw error but after line 2 was executed. It shows that error will be logged only when it is encountered in the program, not at the start itself, unless the error is itself at the start. After the error is logged, program will end abruptly. That is the exact problem, error handling is meant to deal with. With error handling, we can prevent the abrupt ending of the program when error occurs. Let us see how🏸

How to handle the error?

It is all the game of syntax, I cannot emphasize much on that. It is seriously the game of syntax and it is pretty easy and straight-forward. Without digging out more words, let us see in the code itself.

try{
    //code that might contain error
}catch(error){
    //display error or whatever you want.
}finally{
    //this will be executed finally if the error is encountered.
}

As the above code is self-explanatory but for the "explanation's" sake. try will be the container for the error, if there any, in the code piece that is inside it. If the error is encountered, then the catch block will "catch" it and see it has an argument error, well it is upto you, what you want to call it, the argument is just a "variable" sort of thing and always points to the "error" itself. finally block will eventually execute the code that is supposed to be executed in case of error, and note that it is not necessary to have a finally block.

Well in summary, we need the try...catch block to simply execute the fourth line of the above-most example. That's it. Let's see what happens in that case:

errorresolved.png

Some interesting stuff about try...catch

We saw the implementation of try...catch in the above illustration. I think some basic and yet fundamental understanding of the working nature would be a great help in understanding the code properly.

  • try...catch will work only for "runnable" javascript code
    • More clearly, the code must be of pure JavaScript syntax, else it would not simply work.
  • try...catch works synchronously
    • That means that for asynchronous functions, try...catch construct must be inside the function to work.

How to "throw" our own errors?

If we want to throw our own custom written error message, then throw keyword comes to our rescue. How can we achieve the purpose by using this keyword, let's see:

function getProduct(a, b) {
  if (isNaN(a) || isNaN(b)) {
    throw 'Parameter is not a number!';
  }
}

try {
  getProduct(3, 'A');
} catch (e) {
  console.error(e);
  // expected output: "Parameter is not a number!"
}

Important Error Types:

There are plenty of error objects but I would discuss tiny bit about the three of them, they are:

  • Syntax Error: This error, as the name suggests, occurs when a syntactically invalid piece of code is encountered.
  • Reference Error: This error occurs when a variable doesn't exist in the corresponding scope when referenced.
  • Type Error: This error occurs when an operation cannot be perfomed because of inconsistency of the type of the value expected.

That's it for this blog guys

I have covered almost all important aspects of Error Handling in JS but there is more to it. For digging deeper into the topic, I would recommend two good resources that I personally referred for this blog. MDN javascript.info

#iwritecode

#lco

#javascript

#ineuron