The try...catch statement allows you to test a block of code for errors.
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:
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:
<html>
<head>
<script type="text/javascript">
function message()
{
adddlert("Welcome guest!");
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
To take more appropriate action when an error occurs, you can add a try...catch statement.