JavaScript Try…Catch Statement

Posted on 21/09/2009 by

0



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

Whenever your browsing the web pages on the internet, we’ve all seen a JavaScript alaet box telling us there is a runtime error and asking “Do you wish to debug?”.  Error messages like this are maybe useful for developers but not for users. When users normally see errors, they often leave the Web Page.

The try…catch Statement

The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

The Syntax will be:

try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}

The try…catch is also written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example:
It shows that to alert “Welcome geust!” when the button is clicked. However there’s a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. 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.

Input

<html>
<head>
<script type=”text/javascript”>
var txt=””;
function message()
{
try
{
adddlert(“Welcome guest!”);
}
catch(err)
{
txt=”There was an error on this page.\n\n”;
txt+=”Error description: ” + err.description + “\n\n”;
txt+=”Click OK to continue.\n\n”;
alert(txt);
}
}
</script>
</head>

<body>
<input type=”button” value=”View message” onclick=”message()” />
<input type=”button” value=”Delete message” onclick=”message()” />
<input type=”button” value=”Save message” onclick=”message()” />
</body>

</html>


Output

View Message
Delete Message
Save Message

EllaHax

Advertisements
Posted in: Coding, JavaScript