WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Errors - Throw and Try to Catch


try statement tests a code block for errors.

catch statement processing error.

throw statement creates a custom error.

finally statement is executed after the try and catch statements, regardless of whether an exception is triggered.


  JavaScript error

When the JavaScript engine executes JavaScript code, various errors occur.

It may be a syntax error, usually a coding error or a typo caused by the programmer.

It may be a typo or a missing feature in the language (possibly due to browser differences).

It could be an error due to incorrect output from the server or the user.

Of course, it could also be due to many other unpredictable factors.


JavaScript throws errors

When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.

The technical term to describe this is: JavaScript will throw an error.


JavaScript try and catch

try statement allows us to define a block of code that is tested for errors during execution.

catch statement allows us to define a block of code to be executed when an error occurs in the try block.

JavaScript statements try and catch appear in pairs.

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}

JavaScript can Raise Errors

When an error occurs, JavaScript will normally stop, and generate an error message.

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


The throw Statement

throw statement allows us to create custom errors.

The correct technical term is: create or throw an exception .

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

Syntax

throw exception

Exceptions can be JavaScript strings, numbers, logical values, or objects.

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 (err) is thrown.

The exception (err) 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(err) {
        message.innerHTML = "Input is " + err;
    }
}
</script>

</body>
</html>
Try it yourself »

HTML Validation

The code above is just an example.

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1"

You can read more about forms validation in a later chapter of this tutorial.


The finally Statement

The finally statement lets you execute code, after try and catch, regardless of the result:

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}
finally {
    Block of code to be executed regardless of the try /catch result
}

Example

function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try {
        if(x == "") throw "is empty";
        if(isNaN(x)) throw "is not a number";
        x = Number(x);
        if(x > 10) throw "is too high";
        if(x < 5) throw "is too low";
    }
    catch(err) {
        message.innerHTML = "Error: " + err + ".";
    }
    finally {
        document.getElementById("demo").value = "";
    }
}
Try it yourself »