How to use Try.. Catch in Java script
The example 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 output=”"
function callfn()
{
try
{
adddlert(”Welcome guest!”)
}
catch(err)
{
output=”There was an error on this page.\n\n”
output+=”Error description: ” + err.description + “\n\n”
output+=”Click OK to continue.\n\n”
alert(output)
}
}
</script>
</head>
<body>
<input type=”button” value=”View message” onclick=”callfn()” />
</body>
</html>
