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.
Contents
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 tryandcatchblock lets you set an error handling code:trydefines a code of block that will be tested for errors, andcatchdefines a code of block that handles the error.
- The throwkeyword lets you create a new custom error text.
- The finallystatement defines a block of code that will be executed aftertryandcatchno 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:
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:
throw "Value invalid."; // throws a string
throw 406; // throws a numberInput 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:
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:
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.
- finallystatement executes code despite any errors.