Handling Errors

While you may have years of experience working with computers, it’s a good bet that many 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 2.16 shows how to use JavaScript’s try/throw/catch commands to produce a friendly, useful error message. We’ve built this into a simple square root calculator.

To handle errors gracefully:

1.
var ans = prompt("Enter a number", "");
Here’s an ordinary, everyday prompt, which stores its returned value in the ans variable for later use. In this case, we want the user to enter a number. If they do that successfully, JavaScript displays the square ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.