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.
try statement lets you test a block of code for errors. And the
catch statement lets you handle the error.
try statement allows you to define a block of code to be tested for errors while it is being executed.
catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
catch come in pairs:
Block of code to try
Block of code to handle errors
By using an example we can understand the uses of try and catch.
document.getElementById(“demo”).innerHTML = err.message;