Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 16th, 2016
JavaScript Errors: Try and catch

How to work with the errors
– The try statement lets you test the included part of the code for errors.
– The catch statement lets you work with the error and fix it.
– The throw statement lets you create custom/personal errors.
– The finally statement lets you use the code even if there is an error occuring

Example of an error

Lets make a typo!

< !DOCTYPE html>
<html>
    <body>
        <p id="example"></p>
        <script>
            try {
                awolert("this is going to an error!");
            }
            catch(error) {
                document.getElementById("example").innerHTML = error.message;
            }
        </script>
    </body>
</html>

Here we wrote the word ‘awolert’ instead of ‘alert’, this will cause a error and the catch will see this happen and put the error in the “example”.

Try and catch

  • Try: it lets you test a part of code for a bug while it’s executing.
  • Catch: will catch the bug that is in the try and will execute the code inside the catch.

Try and Catch are never apart, they do not work without the other.
The cool thing about try and catch is when they do have an error the code doesn’t stop like it normally does and generate an error, instead here it starts using the catch code.

try {
    //Code to test for errors.
}
catch(error) {
    //Code to fetch the errors and execute code inside here.
}

Throw

This is what a Throw looks like:

throw "It's over";    // text
throw 9000;          // number

Throws can be a String, a Number, a Boolean or an Object.
Let’s make an example:

    var x = "";
    try {
        if(x == "") throw "The String Is Empty!";
    }
    catch(error) {
        message.innerHTML = "The error is: " + error;
    }

The error will show “The String Is Empty” because you put it like that.

Finally

This is a part of the code which ignores the try and catch, it will execute the code that’s in it after the try and catch has been done like nothing happened.

    var x = "";
    try {
        if(x == "") throw "The String Is Empty!";
    }
    catch(error) {
        message.innerHTML = "The error is: " + error;
    }
    finally {
        document.getElementById("example").value = "";
    }

Posted by Mandy van Zetten

Leave a Reply

Your email address will not be published. Required fields are marked *