Try/Catch/Finally Statements

When there is an exception in execution of JavaScript code, it can be handled by surrounding the code with try...catch…finally.  The block of code that has to be tested for exception are surrounded by try. When an error occurs, the try block is stopped and catch block is executed. Errors are customized in throw statements. The statements which have to be executed regardless of errors in the code or not, are processed under a finally block. 

Syntax

try{
    // code containing error. If there is no error
    //all the lines of code in this block are executed.
    //If an error is encountered, the execution seizes at
    //that line and exception is thrown.

catch(exception){
    //This uses a local variable and refer to the error 
    //object. It can also choose to handle or ignore or rethrow 
    //the exception to other block.
    if(exception_1){
        //exception cause for case 1 
    }
    else if(exception_2){
        //exception cause for case 2
    }
    else{
    //general case of exception
    }
}
finally{
    //code to be executed compulsorily.
}

There can be multiple exceptions or errors which have to be caught. In such cases, there can be if-else statements inside catch in order to throw separate errors which helps in debugging.

There can be nested try…catch statements. In such cases, when inner try statement throws an error it gets caught in the inner catch and finally is executed. Then, if the exception is re-thrown the outer catch shows the error.

Example of catch...try...finally statements

try{
    try{
        throw new Error(“error1”);
}catch(ex){
    console.error(“inner”, ex.message);
    throw ex;
}finally{
    console.log(“finally”);
}
} catch(ex){
    console.error(“outer”, ex.message);
}
//Output:
“inner” “error1”
“finally”
“outer” “error1”

With statement

The with statement is a deprecated keyword in JavaScript, and is no longer used. It adds the object present in expression to scope chain till the block completes execution. When the execution of block is completed, object is popped and scope chain returns to previous state. When we try to access variable not in the with scope, it searches outside. We can also use nested with statements.

Syntax

with(object){

   //code related to the expression object

}

Advantages of with statement

The keyword with helps to reference the object parameters within a block. Hence searching for object references in look up table multiple times is reduced. 

Disadventages of with statement

However, the with keyword can be done using a temporary variable, which stores the object reference. Also, the with (object_name) forces compiler to search for specified object in look up first. This is a slow process, as all identifiers which are not part of specified object also has to be searched. Also for better performance, the with should access members of specified object only.

Example of with statement

 

›› go to examples ››