JavaScript Exception Handling – Part II

JavaScript Exception Handling – Part II

In this JavaScript tutorial, you will learn about exception handling viz. try…catch..finally statement and nested try…catch statements along with syntax and examples.

try…catch..finally Statement:

JavaScript has a finally statement that can be used as an optional construct along with try..catch statements. The finally construct placed in a try…catch construct is an optional statement. When the finally statement is placed in a try…catch construct, it always runs following the try…catch structure.

The general syntax of a try…catch..finally statement is as follows:


try
{
…………      
//Block of code which is to be tested for errors
…………
}
catch(err)
{
…………
…………     
//Block of code which is to be executed if an error occurs
}
finally
{
…………
…………    
//This is optional and runs after try and catch structure has run.
}

 

for example:

 


<html>
   <
head>
      <
script type="text/javascript">
        try
        {
           document.write(junkVariable)
        }

        catch(err)
        {
           document.write(err.message + "<br/>")
        }
        finally
        {
           document.write("Finally Block entered: Welcome")
        }

      </
script>
   <
/head>

   <
body>
   </
body>
</
html>

The output of the above program is

‘junkVariable’ is undefined
Finally Block entered: Welcome

In the above program, after the try block is executed, the catch block throws the error. The finally statement is then executed last, displaying the second message “Finally Block entered: Welcome”

Additional usage information about try…catch..finally and throw statements:

Nested try…catch Statements:

It is also possible to have nested try..catch statements or one try..catch statement placed inside another.

for example:


try{
      ………           
//Block of code
      ………           
//Block of code
      try
      {
         ………        
//Block of code
         ………        
//Block of code
      }
      catch(Err)
      {
         ……..         
//Block of code
         ……..         
//Block of code
      }
      ……..           
 //Block of code
      ……..           
 //Block of code
}
catch(err1)
{
     ……..           
    //Block of code
     ……..             
//Block of code
}

finally

{

     ……..                //Block of code
     ……..             
//Block of code
}

* It is also possible to catch the error placed in the inner try..catch statement, then use that error in the outer catch statement of the nested try..catch statement using the throw statement of JavaScript.

* Using the throw statement, it is possible for the programmer to throw errors at any point.

[catlist id=157].

Related posts