When ever there is an exception in execution of JavaScript code, it can be handled by wrapping up the code in try...catch…finally statements.  These methods are considered to be amongst the most often used error intercepting techniques in javaScript. More about try-catch-finally can be found following this link.

The block of code that has to be tested for exception is surrounded by try statement. The error caught during try block execution than gets handled within the catch statement. When and error occurs, the try block is stopped and the catch” block is executed. Errors may be customized within throw statements. Following an error being "caught" or not, a finally statement may be added to execution that will be executed regardless if an error has occured or not.

NOTE: These statements do not catch syntax errors. Instead these statements may be used if there are logical errors which occur within the code script.

Syntax for try-catch-finally statements

try{
        // code containing error
}catch(exception){
    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 could be caught. In such cases, there can be if-else statements inside the catch to throw separate errors which in turn will help in debugging.

There are 3 variations of try/catch blocks:

  • try…catch
  • try…finally
  • try…catch…finally

Example of try-catch-finally statements

The JavaScript code in this example tries to access an HTML variable which is not defined. When the script is ran, the lines of code following the error are not executed. The error is caught in catch block and finally is executed.

 

 

›› go to examples ››