Error Handling Basics

When an error occurs while executing a block of code, JavaScript will normally stop and generate an error message. JavaScript will actually create an Error object with two properties: name and message.

The technical term for this is: JavaScript will throw an exception (throw an error).

You can handle errors in Javascript using try and catch block.

JavaScript try and catch

The JavaScript statements try and catch come in pairs.

try

The try statement allows you to define a block of code to be tested for errors while it is being executed.

catch

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Catching is done by wrapping a piece of code in a try block, followed by the keyword catch.

Syntax
try {
    Block of code to try
}
catch(ex) {
    Block of code to handle errors
}
JavaScript Throws Errors

When the code in the try block causes an exception(throws an error), the catch block is evaluated. The variable name (in parentheses) after catch will be bound to the exception value. After the catch block finishes or if the try block finishes without any problems, control proceeds further below the entire try/catch statement.

The throw Statement

The throw keyword is used to raise an exception. The throw statement allows you to create a custom error.

You can throw any exception (throw an error) as you wanted.

The exception can be a JavaScript String, a Number, a Boolean or an Object.

throw "Too big";    // throw a text

throw 500;          // throw a number

If you use throw together with try and catch, you can control program flow and generate custom error messages.

Input Validation Example

This example examines input. If the value is wrong, an exception (ex) is thrown.

The exception (ex) is caught by the catch statement and a custom error message is displayed:

<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="message"></p>
<script>
function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "") throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 5) throw "too low";
        if(x > 10) throw "too high";
    }
    catch(ex) {
        message.innerHTML = "Input is " + ex;
    }
}
</script>
 
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents