Page 1 of 1

Try and Catch Error Handling Rate Topic: -----

#1 kewlkreator  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 37
  • View blog
  • Posts: 1,065
  • Joined: 25-March 09

Posted 30 August 2009 - 12:52 PM

Welcome!
In this tutorial, I'll show you how to deal with errors in javascript. For example, if you wrote a bad statement, this script would catch it!

How/
To do this, we use the Try and Catch statements. Try will "try" a function or statement. Catch will do something with that. Another way to think of it is as a If and Else statement.

Our "error"
Ok, for this tutorial to have a purpose, you have to make a mistake. It could be a misspelling, null variable, etc. Yes, I know you're perfect with JS but bear with me. I'll use:
my.document.write(-Hi-);

Whoops!

Grouping
Lets group this in a function so we don't have to call it repeatidly.
function error() {
my.document.write(-Hi-);
}


Try and Catch
Time for some error management!
function handle() {
try {
	 error();
	 //Returns an error
} catch(err) {
	 //Error handeling code
	 window.alert("ERROR!");
}
}

See how it relates to If and Else? I put it in a function so that we can call it simpily.

Calling it
Lets do a bit of HTML that will call our handle(); function.
<html>
<body>
<script>function error() {
my.document.write(-Hi-);
}
// The error
function handle() {
try {
     error();
     //Returns an error
} catch(err) {
     //Error handeling code
     window.alert("ERROR!");
}
}
//Handeling code
</script>
<input type="button" onclick="handle()" value="Try"/>
</body>
</html>

Run it and see what happens!

Furthermore...
If you want to catch the error description, use
window.alert(err.description);


Thanks!
Thanks for reading!
~kewlkreator

Is This A Good Question/Topic? 0
  • +

Replies To: Try and Catch Error Handling

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3390
  • View blog
  • Posts: 9,581
  • Joined: 08-June 10

Posted 11 June 2010 - 12:38 AM

View Postkewlkreator, on 30 August 2009 - 07:52 PM, said:

Furthermore...
If you want to catch the error description, use
window.alert(err.description);


be aware that this is IE specific code. W3C compliant browsers use the .message property instead. (ref.)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1