How To Handle Errors In JavaScript

Finding and squashing bugs in complex codes sometimes is a really tedious task. Each code line needs to be analyzed to find the error. Instead of doing so, JavaScript has an easy yet innovative technique to handle this by using inbuilt error handling methods for example – try-catch.

Try-Catch in JavaScript

Errors in JavaScript can range from Reference errors to Syntax errors. A minimal try-catch code looks like this:

try {
  var a = x + y;
  console.log(a);
} catch (err) {
  console.log("An error occured during calculation");
}

If you observe correctly this will give a Reference error because x and y are not declared. This try-catch code gives a custom error message which can be curated by the programmer. If the error message needs to be viewed the err aka the error needs to be logged to the console.

This error message can be customized to indicate the line of code or where the error is expected to take place.

Types of Errors in JavaScript

  1. EvalError – This happens when an error has occurred in the eval() function. The eval() function is used to evaluate expressions in JavaScript.
  2. RangeError – This error occurs when a value is tried to pass when it is outside the range.
  3. ReferenceError – This error is thrown when a variable that is not declared is referenced.
  4. SyntaxError – This error occurs when the syntax of the code is wrong.
  5. TypeError – This error is thrown when you use an unexpected value.
  6. URIError – On using illegal characters this error occurs.

Throw Statement in JavaScript

The throw statement allows the developer to create a custom error.

An example of this is:

try {
  var a = x + y;
} catch (err) {
  throw "error";
}

The throw function helps one to design better error management systems. The throw function raises an exception and causes the code to terminate. If the same thing was substituted with console.log or console.error then the code is not terminated.

Finally

The finally statement lets you execute the code notwithstanding the output of the try-catch statements. An example of the same is:

try {
  var a = x + y;
} catch (err) {
  console.error(err);
}
finally{
  console.log("CodeSpeedy");
}

On executing the above code we see that even though an error is shown, the code in the finally statement still executes. The finally statement can be assumed as an else statement in the if-else condition.

Conclusion

JavaScript provides a lot of ways to tackle errors. Each error handling has its own special functionality.

You can also read,

How To Add Elements In JSON Array Using JavaScript

Plotting A Line Graph Using JavaScript with Chart.js

Leave a Reply

Your email address will not be published. Required fields are marked *