Home » Tutorials » JavaScript » Try and Catch

Try and Catch

JavaScript has a great way to deal with errors. Try and catch are a way to handle errors. Normally, if an error occurs, a couple of things might happen:

  • The browser will error silently causing some JavaScript code around the where the error occurred not to be executed.
  • The browser will create annoying pop up boxes alerting the user that an error occurred.

Neither of the following options are ideal, which is why we like to handle errors on our own. Let me start by not suggesting that your whole code is written in a try/catch statement. While that may not be a terrible idea for beginners, it is extremely impractical. Generally, I will use try/catch statements when dealing with user input. Of course, there are many of great reasons to use try/catch statements.

When you are writing JavaScript, try to think of how your code could possibly mess up and cause an error. If you can think of way that it is possible, use a try/catch statement.

Example
                var animalArray = new Array("Meerkat","Dog","Squirrel");
                var userInputVariable = document.getElementById('exampleTextField').value;
                try
                {
                    document.getElementById('inputTest').innerHTML = animalArray[userInputVariable].length;
                }
                catch(e)
                {
                    document.getElementById('inputTest').innerHTML = "Please type a 0, 1, or 2.";
                }

Let’s say for some random reason we want a user to enter a number between 0 and 2. Whatever number they enter will return the length of that item in the array. If the user enters a 0, which is “Meerkat” in our animal array, our code will output 7 in our div with an id of inputTest. When a 1 is entered, the output is 3. However, if the user inputs a 4, we cannot check the items length because it doesn’t exist. Normally, we would get an error here, and in fact, we do. Since we caught the error with catch, we can tell the browser what to do instead of what it would normally do when it finds the error. In this case, we change our div inputTest to show “Please type a 0, 1, or 2.”

To make our try/catch error handling even smoother, throw can help us break down the error even more.

Example
                var animalArray = new Array("Meerkat","Dog","Squirrel");
                var userInputVariable = document.getElementById('exampleTextField2').value;
                try
                {
                    if(userInputVariable > 2)
                    {
                        throw "Err1";
                    }
                    else if(userInputVariable < 0)
                    {
                        throw "Err2";
                    }
                    else if(isNaN(userInputVariable))
                    {
                        throw "Err3";
                    }
                    else
                    {
                        document.getElementById('inputTest2').innerHTML = animalArray[userInputVariable].length;
                    }
                }
                catch(e)
                {
                    switch(e)
                    {
                        case "Err1":
document.getElementById(‘inputTest2’).innerHTML = “That value is too high.”; break; case “Err2”: document.getElementById(‘inputTest2’).innerHTML = “That value is too low.”; break; case “Err3”: document.getElementById(‘inputTest2’).innerHTML = “That value is not a number.”; break; default: document.getElementById(‘inputTest2’).innerHTML = “Please type a 0, 1, or 2.”; break; } }

Look at all of that code. It might be somewhat lengthy, but test this result out with the result from the earlier example. It actually shows the user what they are doing wrong, rather than the blanket statement of “Please type a 0, 1, or 2.” We are putting conditions into our try statement. If the user input satisfies any of our conditions, except for the else, we will throw a certain type of error. For instance, when the user inputs a 4, it will satisfy the condition of userInputVariable > 2, which will throw an error of “Err1”. When it throws the error, catch will start running. Since our current error is Err1, when will execute the statements in the case “Err1”:. The statement will change inputTest‘s value to “That value is too high.” Always try to use the some sort of fallback plan when using throw. In my example, my fallback plan is my default in the switch statement.

References



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Try and Catch". After Hours Programming. Accessed on March 17, 2024. https://www.afterhoursprogramming.com/tutorial/javascript/try-and-catch/.

  • Stewart, Suzy. "Try and Catch". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/javascript/try-and-catch/. Accessed 17 March, 2024.

  • Stewart, Suzy. Try and Catch. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/javascript/try-and-catch/.



Leave a Comment

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