Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Handling Errors

While you may have years of working with computers, it's a good bet that most of your site's visitors won't. Consequently, you'll want to give them meaningful error messages instead of the technobabble that most browsers return if they object to something the user does. Script 3.10 shows how to use JavaScript's try/throw/catch commands to produce a friendly, useful error message.


Script 3.10 Use this script to have JavaScript handle errors gracefully.

To handle errors gracefully

  1. ans = prompt("Enter a number","") Here's an ordinary, everyday prompt. In this case, we want the user to enter a number. If they do that successfully, JavaScript will display the square root of whatever they entered.
  2. try { However, if they didn't enter a number, as in Figure 3.14 , we want to be able to catch it gracefully and display something meaningful. We start off by using the try command. Inside its block of code, we'll check to see if the user's entry was valid.

    Figure 3.14 We want a number, but the user could enter anything.

  3. if (!ans || isNaN(ans)) {
      throw new Error("Not a valid
       U2192.GIF number")
    There are two things we care about: no entry at all, or if the user entered something but it was non-numeric. If !ans is true, that means that the user didn't enter anything. The built-in isNaN() method checks to see if the parameter it's passed is "Not a Number." If isNaN() returns true, we know that something invalid was entered. In either case, we want to throw an error; in this case, it will say "Not a valid number." Once an error is thrown, JavaScript jumps out of the try block and looks for a corresponding catch statement. Everything between here and there is skipped over.
  4. alert("The square root of " + ans +
    U2192.GIF " is " + Math.sqrt(ans))
    If something valid was entered, the square root is displayed, as shown in Figures 3.15 and 3.16 .

    Figure 3.15 Here's the number we wanted.


    Figure 3.16 And here's the result of the script acting on the number.

  5. } This closing brace ends the try block.
  6. catch (errMsg) {
    Here's the promised and looked-for catch statement. The error is passed in as a parameter, and the message part of the error is displayed ( Figure 3.17 ). If no error was thrown, the code inside the catch will never be executed.

    Figure 3.17 If bad data was entered, let the user know.

  • + Share This
  • 🔖 Save To Your Account