School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,108 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,046 people online right now. Registration is fast and FREE... Join Now!




Try and Catch Error Handeling

 
Reply to this topicStart new topic

> Try and Catch Error Handeling

kewlkreator
Group Icon



post 30 Aug, 2009 - 11:52 AM
Post #1


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:
Error
my.document.write(-Hi-);

Whoops!

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


Try and Catch
Time for some error management!
CODE

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
<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
CODE
window.alert(err.description);


Thanks!
Thanks for reading!
~kewlkreator

Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 12:41PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month