How To Handle Errors In JavaScript

Posted by TotalDC

When writing code several reasons may cause errors, for example:

  • A problem with network connection
  • A user might have entered an invalid value in a form field
  • Referencing objects or functions that do not exist
  • Incorrect data being sent to or received from the web server
  • A service that the application needs to access might be temporarily unavailable

These types of errors are known as runtime errors because they occur at the time the script runs. A professional application must have the capability to handle such runtime errors gracefully. Usually, this means informing the user about the problem more clearly and precisely.

The try catch In JavaScript

JavaScript has the try-catch statement to trap the runtime errors, and to handle them. Any code that might throw an error should be placed in the try block of the statement, and the code to handle the error is placed in the catch block. Here’s how it looks:

try {
    // Code that may cause an error
} catch(error) {
    // Action to be performed when an error occurs
}

If an error occurs at any point in the try block, code execution is immediately transferred from the try block to the catch block. If no error occurs in the try block, the catch block will be ignored, and the program will continue running after the try-catch statement. Here’s an example:

try {
    let greet = "Hi, there!";
    document.write(greet);
    
    // Trying to access a non-existent variable
    console.log(welcome);
    
    // If error occurred following line won't execute
    alert("All statements are executed successfully.");
} catch(error) {
    // Handle the error
  alert("Caught error: " + error.message);
}
 
// Continue execution
console.log("<p>Hello World!</p>");

The code in the example will generate an error that is displayed in an alert dialog box, instead of printing it to the browser console. Besides that, the program didn’t stop abruptly even though an error had occurred.

The try catch finally In JavaScript

The try-catch statement can also have a finally clause. Code from finally block of code will always execute, even if an error occurred in the try block. Here’s an example:

// Assigning the value returned by the prompt dialog box to a variable
let num = prompt("Enter a positive integer between 0 to 100");

// Storing the time when execution start
let start = Date.now();

try {
    if(num > 0 && num <= 100) {
        alert(Math.pow(num, num)); // the base to the exponent power
    } else {
        throw new Error("An invalid value is entered!");
    }
} catch(e) {
    alert(e.message);
} finally {
    // Displaying the time taken to execute the code
    alert("Execution took: " + (Date.now() - start) + "ms");
}

Throwing Errors In JavaScript

Now you know how errors thrown by JavaScript parsers occur. But you can throw an error manually by using a throw statement.

The throw expression can be an object or a value of any type. However, it is recommended to use objects with name and message properties. JavaScript built-in Error() constructor provides a way to create an error object. Here’s an example for you:

throw 123;
throw "Missing values!";
throw true;
throw { name: "InvalidParameter", message: "Parameter is not a number" };
throw new Error("Something went wrong");

In the next example, there will be a function squareRoot() to find the square root of a number. It will return NaN for negative numbers without providing any hint on what was wrong in your code. Let’s look of how you can fix this issue:

function squareRoot(number) {
    // Throw error if number is negative
    if(number < 0) {
        throw new Error("Unable to calculate square root of a negative number.");
    } else {
        return Math.sqrt(number);
    }
}
    
try {
    squareRoot(16);
    squareRoot(625);
    squareRoot(-9);
    squareRoot(100);
    
    // If error is thrown following line won't execute
    console.log("All calculations are performed successfully.");
} catch(e) {
    // Handle the error
    console.log(e.message);
}

Error Types In JavaScript

Error object is the base type of all errors and it has two main properties – a name property that specifies the type of error, and a message property that holds a message describing the error for the user. Any error thrown will be an instance of the Error object.

There are several different types of error that can occur during the execution of a JavaScript program, such as SyntaxError, TypeError, and URIError, RangeError, ReferenceError.

RangeError In JavaScript

A RangeError occurs when you use a number that is outside of the range of values. For example, creating an array with a negative length will give you a RangeError.

let num = 12.735;
num.toFixed(200); // throws a range error

let array = new Array(-1); // throws a range error

ReferenceError In JavaScript

A ReferenceError occurs when you try to reference or access a variable or object that doesn’t exist. Here’s an example:

let firstName = "Harry";
console.log(firstname); // throws a reference error 

undefinedObj.getValues(); // throws a reference error

nonexistentArray.length; // throws a reference error

SyntaxError In JavaScript

A SyntaxError occurs at runtime if there is any syntax problem in your JavaScript code. For example, if closing bracket is missing etc.

let array = ["a", "b", "c"];
console.log(array.slice(2); // throws a syntax error

console.log("Hello World!'); // throws a syntax error

TypeError In JavaScript

A TypeError occurs when a value has the wrong type. For example, if you are calling a string method on a number etc.

let num = 123;
num.toLowerCase(); // throws a type error 

let greet = "Hello World!"
greet.join() // throws a type error 

URIError In JavaScript

A URIError occurs when you specify an invalid URI to the URI-related functions. Here’s an example:

let a = "%E6%A2%B";
decodeURI(a);  // throws a URI error

let b = "\uD800";
encodeURI(b);   // throws a URI error

Last time we covered JSON parsing in JavaScript, you can find that article here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.