April 23, 2009

0 JavaScript Try Catch Statements

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

JavaScript - Catching Errors

There are two ways of catching errors in the webpage:

By using the try...catch statement (available in IE5+, Mozilla 1.0, and Netscape 6)

By using the onerror event.This is the old standard solution to catch errors (available since Netscape3)

Try...Catch Statement

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

Syntax

try
(
// Run some code here
)
catch (identifier)
(
// Handle exceptions here
)

Note that try...catch is written in lowercase letters, Using uppercase letters will generate a JavaScript error!

Example 1

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 addlert().A Javascript error occurs.

<html>
<head>

<body>
<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

The tutorial below contains the "Welcome guest !" example rewritten to use the try...catch statement.Since alert() is misspelled, a JavaScript error occurs.However, this time , the catch block catches the error and executes a custom code to handle it.The code displays a custom error message informing the user what happened.

<html>
<head>
<script type="text/javascript">
var txt =" "
function message( )
{
try
{
addlert ( "Welcome guest 1")
}
catch (err)
{
txt ="There was an error on this page. \n \n"
txt+="Error description: " + err.desctiption + "\n \n"
txt ="Click Ok to contine. \n\n"
alert ( txt )
}
}
</head>
<body>
<input type =" button" Value= "View message" onclick="message" )
</body>
</html>







0 comments:

Post a Comment

Blogger Themes

 
Powered by Blogger