JavaScript Errors - Try...Catch
(Page 2 of 4 )
You ever play a game of football with a kid that throws the ball way too hard and is always yelling at you, “Hey, try and catch this!” He always throws the ball and you always drop it, but not before it has a chance to leave a giant purple indentation in your puny chest. After a while you just give up on it and never play with the kid any more. Yet another programmer has been born.
If you have ever been on a website and had a run-time error pop up you know how annoying it is. It asks you the dumbest question on earth: do you wish to debug? For the nine billion people on Earth that aren't programmers, they just stare at this message blankly. If they click no, then stuff doesn't work right. If they click Yes, they get brought into a strange new world where absolutely nothing makes sense. Either way, they are never coming back to your page.
To solve this problem, we could use either of the onerror Events you saw before, or a Try...Catch statement.
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Hey There Pilgrim!")
}
catch(err)
{
txt="An error has occurred.nn"
txt+="Type of error: " + err.description + "nn"
txt+="Press OK to continue.nn"
alert(txt)
}
}
</script>
</head>
<body>
<input type="button" value="Trigger the Error" onclick="message()" />
</body>
</html>
The above code works similar to the OnError code in the previous example. Again, we create a function to greet the user that is doomed to fail, and when it does, it triggers our Try...Catch statement, which creates a pop-up error to alert the user that something has gone wrong and asks them to click the OK button. When they do, it returns them to the page.
But what if we don't want it to simply return them back to the page? I mean, there is an error on it after all. We could always give them the option to return, say, to the home page:
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Howdy Pilgrim!")
}
catch(err)
{
txt="An error occurred on this page.nn"
txt+="Press OK to continue on this page,n"
txt+="or Press Cancel to return to our home page.nn"
if(!confirm(txt))
{
document.location.href="http://www.devshed.com/"
}
}
}
</script>
</head>
<body>
<input type="button" value="Click Me to Trigger the Error" onclick="message()" />
</body>
</html>
Again, this code does the same as our previous code, however instead of using an alert box to inform the user that an error has occurred, we use a Confirm box. The confirm box gives the user two options: Click Ok and remain on the page with the errors, or click Cancel and return to the home page.
Next: Throwing the Ball (and Exceptions) >>
More JavaScript Articles
More By James Payne