Monday, 23 April 2012

Javascript Exception Handling

Exception Handling is one of the most important and essential while programming in JavaScript.  If the exception is not handled properly then we may end up in exclamatory mark that will appear in the left bottom corner of the page. This is due to some exception or error that is available in the executed page. These JavaScript is a client side script so execution failure occur only in the browser from the client end and not in server

There are two ways of handling exception.


1.  Placing the code between the try and catch block. It is the most the easiest approach for error such as “Object not Found” exception/error.
Eg:
try
{
//JavaScript Code
}
catch (e)
{
}
Code:
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
try{
var servervalue = "two";
for(var i=0; i<document.getElementById("ItemLists").options.length; i++) {  
if ( document.getElementById("ItemLists").options[i].text == servervalue )
{   
  document.getElementById("ItemLists").selectedIndex = i;       break;
}
}
}
catch(e){ alert('Control Not Found!!!');}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>


2.  Another option is using null check, check to see a control available in the rendered page in the browser.
Eg:  If(Document.all("ItemLists") != null)


Code: 
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
var servervalue = "two";
//null check to see the control "ItemLists" available     in the html page
if (document.getElementById("ItemLists")!=null){
for(var i=0;  i<document.getElementById("ItemLists").options.length; i++)
{  
if (document.getElementById("ItemLists").options[i].text == servervalue )
 {   
  document.getElementById("ItemLists").selectedIndex = i;    
  break;  
 }
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>

No comments:

Post a Comment