- 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.
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.
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.
Your code will execute in this window.
Let's explore some more tutorials or topics!
No comments yet... Be the first!