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






MultiQuote





|