- Detecting Browser Plug-ins
- Around and Around with Loops
- Writing with Loops
- Using For/In Loops
- Using Do/While Loops
- Checking if Java Is Enabled
- Functions
- Using Multi-level Conditionals
- Working with Functions That Return Values
- Handling Errors
- Putting More than One Script on a Page
- Scrolling Status Bars
- Status Bar Messages
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
- 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.
-
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.
-
if (!ans || isNaN(ans)) { throw new Error("Not a valid
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.number") }
-
alert("The square root of " + ans +
If something valid was entered, the square root is displayed, as shown in Figures 3.15 and 3.16 ." is " + Math.sqrt(ans))
Figure 3.15 Here's the number we wanted.
Figure 3.16 And here's the result of the script acting on the number.
- } This closing brace ends the try block.
-
catch (errMsg) { alert(errMsg.message) }
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.