Error handling, “try..catch”

No matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.

Usually, a script “dies” (immediately stops) in case of an error, printing it to console.

But there’s a syntax construct try..catch that allows us to “catch” errors so the script can, instead of dying, do something more reasonable.

The try statement lets you test a block of code for errors. And the catch statement lets you handle the error.

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
}

By using an example we can understand the uses of try and catch.

<p id=”demo”></p>