JavaScript Errors – A Comprehensive Guide to master Error Handling
Free Web development courses with real-time projects Start Now!!
There often comes a situation when you run into an error that may or may not be fatal for your application. After learning all you did on JavaScript Garbage Collection, I think you are ready to explore what all the errors we stumbled upon in our previous tutorials. We saw many errors, including ReferenceError and SyntaxError while we tried to understand various JavaScript concepts. This tutorial will help you understand why we get them and how to resolve them. Let’s get on with the concept by first understanding what JavaScript errors actually are.
What do you mean by Errors?
What is the first thing you get when you read the word “error”? It may be a mistake, wrong, incorrect, fault, misinterpretation, etc. You will be correct in some ways, not so much in others. Okay, okay. I’ll stop being so cryptic and help you understand it all in simpler terms.
In programming, an error is a piece of code that disrupts the normal program flow. The same definition applies to JavaScript, but with an additional factor. While working in JavaScript, if your code throws an error, the JavaScript interpreter will stop the execution of the program that instant. Do not think of JavaScript errors as your adversaries, they can be your best friends while developing a new application. The only way you can debug your JavaScript code is by utilizing the errors and warnings the best you can. You can observe any error, along with the line in which the error occurred, in your browser console window.
In JavaScript, we use the Error constructor to create an error object. Every time a runtime error occurs, the script throws an Error instance. You can create an error object in the following manner:
new Error([msg]);
In the above statement, all the parameters are optional, but you need to remember the order of their appearance. The msg is a human-readable description of the error.
Error as a Function
You can use Error as a function, by skipping the new keyword. You will get the same output as above: a new Error object. For example, the following statement creates a new Error object:
const err = Error(“We created this error using the function call.”);
Don’t forget to check – Methods to Create JavaScript Objects
Types of JavaScript Errors
1. EvalError
This error creates a JavaScript instance that represents an error occurrence concerning the global function eval(). Newer versions of JavaScript don’t throw these errors. Instead, they rely on SyntaxError.
2. RangeError
It creates an Error instance that occurs when a numeric value or parameter exceeds its allowed range.
3. ReferenceError
This error occurs while de-referencing an invalid reference and creates an instance for the same. Dereferencing refers to getting a value stored in memory using another object.
4. SyntaxError
This script raises this error and creates an instance when a syntactically incorrect statement occurs while parsing the JavaScript code.
5. TypeError
This error occurs when a variable or parameter does not have a valid data type. One such instance where you get a TypeError instance is when you try to perform numeric calculations on a String object.
6. URIError
It occurs and creates an error instance when the encodeURI() or decodeURI() methods have incorrect parameters.
Time to gain expertise in JavaScript Number Methods
The try, catch and finally statements
JavaScript consists of three blocks associated with error handling: try, catch and finally. The try block catches whatever exception occurs in the program and throws it to the catch block. When any of the above errors occur at runtime, the script uses throw internally to send program control to the catch block. The finally block is optional with a try-catch block. The statements inside this block execute regardless of an error occurring. The catch block must be followed by either exactly one catch or a finally block or one of both. The syntax for a try…catch…finally statements looks like this:
try{ // statements to execute [break;] } catch(exception){ // statements if an error occurs [break;] } finally{ // statements that always execute }
You will create a JavaScript program to implement these statements before this tutorial ends.
Note: The try-catch statements only work with runtime errors, thus you cannot handle SyntaxError with their help. If SyntaxError occurs, the script shows the error in the console window, rather than performing error handling.
Throwing a Generic Error in JavaScript
It is very easy to throw an error when you want to do so. This is possible with the help of the JavaScript keyword throw that raises the specified error. You are free to throw any error you might want as per your requirements.
Code:
<html> <body> <script> try{ // try block searches for an error throw new Error("Oops, try again!"); // throwing an error intentionally } catch(e){ // control jumps over to the catch block when error found document.write(e.name + ": " + e.message); //message to print when error occurs } </script> </body> </html>
Screenshot:
Output:
The onerror() method
This was the very first feature to introduce error handling in JavaScript. This event fires whenever an error occurs on the page. It provides three pieces of information to identify the exact nature of the error. These are:
- Error message – It is the same message that the browser would display for the given error.
- URL – It is the file location where the error occurred.
- Line number – It is the line number in the given URL that caused the error.
The following JavaScript program throws an error on the page and extracts the above three details.
Code:
<html> <body onload = "myFunc();"> <p></p> <p></p> <script> //function executed when error occurs window.onerror = function (msg, url, line) { document.querySelectorAll('p')[0].innerHTML = "An error occurred on the page."; document.querySelectorAll('p')[1].innerHTML = "<b>Message :</b> " + msg + "</br><b>url :</b> " + url + "</br><b>Line number :</b> " + line; } </script> </body> </html>
Screenshot:
Output:
Handling a Specific Error in JavaScript
Unlike other programming languages like Java, defining multiple catch blocks is invalid in JavaScript. There is another way in JavaScript that allows you to handle specific errors in your program and work accordingly. You can check for multiple errors in a JavaScript program by following the code below.
Code:
<html> <body> <h3>DataFlair: try-catch-finally statements</h3> <script> var num1; try{ // try block var num1 = num2 * 4; // you cannot use the reference for num2 // creates an Error object and throws it to the catch block document.write("This is an additional line.</br>"); // this line is skipped } catch(e){ // catch block if(e instanceof ReferenceError) document.write("Reference Error</br>"); else if(e instanceof SyntaxError) document.write("Syntax Error</br>"); else document.write("Other Error</br>"); } finally{ //finally block document.write("This statement executes whether an error occurs or not.</br>"); } </script> </body> </html>
Screenshot:
Output:
Custom Errors
To define your error in a JavaScript program, the first thing you need to do is create your error class that extends the functionality of the Error class in your program. Then you throw your custom exception in the try-catch block to deal with it. The following program defines a custom error in the program and produces the desired output.
Code:
<html> <body> <script> class myCustomError extends Error{ // constructor function constructor(team, course = "JavaScript"){ super(team, course); // assigning values to the myCustomError object this.name = "myCustomError"; this.team = team; this.course = course; } } try{ // try block throw new myCustomError("DataFlair"); // custom error thrown }catch(e){ // catch block document.write("<b>" + e.name + "</b></br>"); document.write("Team: " + e.team + "</br>"); document.write("Course: " + e.course + "</br>"); } </script> </body> </html>
Screenshot:
Output:
Summary
In this tutorial of DataFlair’s JavaScript tutorial series, we studied about JavaScript Errors. We discussed different errors that occur in JavaScript, along with the various methods to prevent the program to stop the execution. We understood how to handle a general as well as a specific exception. We also created our own error class in JavaScript.
Next tutorial to explore – JavaScript Style Attribute
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google