Create a Website
CSS Tutorial
FREE Hosting!
With every domain name
you register at DotEasy
you get FREE (no-ad)
one year hosting.
PLUS you get:
  • FREE Website Builder
  • FREE Blog
  • FREE Forum
  • FREE Photo Album
  • FREE Email Accounts
Get your FREE hosting today!
Home > JavaScript Tutorial
$0 Web Hosting

The try...catch statement allows you to test a block of code for errors.

JavaScript Try...Catch Statement

When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

This chapter will teach you how to trap and handle JavaScript error messages, so you don't lose your audience.

There are two ways of catching errors in a Web page:

Try...Catch Statement

The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

The example below contains a script that is supposed to display the message "Welcome guest!" when you click on a button. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs:

The Code

<script type="text/javascript">
function message()
adddlert("Welcome guest!");
<input type="button" value="View message" onclick="message()" />

To take more appropriate action when an error occurs, you can add a try...catch statement.

Enjoy this tutorial?

1. Link to this page(copy/paste into your own website or blog):
2. Add this page to your favorite social bookmarks sites:
3. Add this page as your favorites. (Press Ctrl+D)