Sunday, May 13, 2018

JavaScript Errors - Throw and Try to Catch

The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, afeter try and catch, regardless of the result.

Errors Will happen!

When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable thing.

Example

In this example we have written alert as adddlert to deliberately produce an error:
<p id="demo"></p>

<script>
try {
    adddlert("Welcome guest!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
</script>
Try it Yourself »
JavaScript catches adddlert as an error, and executes the catch code to handle it.

JavaScript try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
try {
    Block of code to try}
catch(err) {
    Block of code to handle errors}

No comments:

Post a Comment