🚨 $100K in Sight: Follow Bitcoin’s Final Push Live! TRACK NOW

Code has been added to clipboard!

Discover JavaScript try catch: Handling JavaScript Error Easily

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

There are various practices for handling errors depending on their origin. One of the options is JavaScript try catch. In this tutorial, you will learn about JavaScript try catch, what it is, and how it works.

In addition to JavaScript try catch, you will learn about JavaScript throw statement, which is used together with try catch to provide more user-friendly error handling, and the finally statement, which is used to provide additional functionality when handling JavaScript errors.

JavaScript try catch: Main Tips

  • Errors often occur when executing JavaScript code. There can be different kind of errors: programmer errors, wrong input, etc.
  • The try and catch block lets you set an error handling code: try defines a code of block that will be tested for errors, and catch defines a code of block that handles the error.
  • The throw keyword lets you create a new custom error text.
  • The finally statement defines a block of code that will be executed after try and catch no matter if there was an error or not.

Collaboration Between try and catch

Whenever we wish to test our code for errors, we first have to choose a specific piece to try. This will help us locate an error and save time that we would waste solving it.

The try statement defines this piece of code that will be tested for any possible errors. Now, once an error occurs within the try statement's block of code, the system will execute the code defined by the catch statement.

As you might have understood, these two statements work together, so they always come in pairs. See the example below to get a better understanding of how they work:

Example
try {
    alert("Hey!");
}
catch(err) {
    document.getElementById("error").innerHTML = err.message;
}

Using throw Statement

The throw statement lets you create a new custom error text. It is often used together with try and catch statements in order to control the flow of the program.

You can set a custom throw statement to appear for each condition defined whenever an error occurs in try block of code. As you can see in the code snippet below, it can throw a text, number or boolean:

Example
throw "Value invalid."; // throws a string
throw 406; // throws a number

DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

Input Validation Example

In the example below, whenever any of the conditions defined in the try block of code are not met, the error occurs. Then, it is caught by the catch statement, and the error message is thrown.

When the user inputs a wrong value, an error message is displayed:

Example
function errorFunction() {
    var errorMsg, x;
    errorMsg = document.getElementById("out");
    errorMsg.innerHTML = "";
    x = document.getElementById("test").value;
    try { 
        if(x == "") throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 1) throw "number is too low";
        if(x > 100) throw "number is too high";
    }
    catch(err) {
        errorMsg.innerHTML = "Input is " + err;
    }
}

finally Statement

The finally statement executes its block of code regardless of the results of the try and catch blocks actions.

In the example below, the finally statement defines a block of code which clears out the input upon clicking the Submit button. This action occurs whether there was an error or not:

Example
function errorFunction() {
    var errorMsg, x;
    errorMsg = document.getElementById("out");
    errorMsg.innerHTML = "";
    x = document.getElementById("test").value;
    try { 
        if(x == "") throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 1) throw "number is too low";
        if(x > 100) throw "number is too high";
    }
    catch(err) {
        errorMsg.innerHTML = "Input is " + err;
    }
    finally {
      document.getElementById("test").value = "";
    }
}

JavaScript try catch: Summary

  • JavaScript try catch method allows you to catch errors in a program.
  • JavaScript throw allows you to set a specific error message to be thrown.
  • finally statement executes code despite any errors.