Error Handling

When executing JavaScript code, different errors can occur. Errors can be coding errors made by the programmer, errors due to wrong syntax, and other dynamic things. try block should be followed by at least one catch-block, or a finally-block, must be present.


try..catch

A try block consist of statements block. It should always be in {}. A catch-block contains statements that specify what to do if an exception is thrown in the try-block. If any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. If no exception is thrown in the try-block, the catch-block is skipped.

try {
throw 'myException'; // generates an exception
} catch (e) {
console.log(e) // catches exception and prints 'myException'
}

finally

The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception.

Following is an example

try {
        var a = 10; // no error block
        } finally () {
          console.log('finally') // this block will run always irrespective of error in try block.
        }