Home Javascript Error Handling in Java Script
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Error Handling in Java Script

Advertisement
In this article you will Learn how to handle error in java script.

Error Handling in Java Script

       

In this article you will Learn how to handle error in java script.
JavaScript is scripting language used for client side scripting. and error are handling in two ways.

  *try...catch statement
  *onerror event

Try...Catch Statement
The try...catch statement grants an exception in a statement block to be captured and handled. Remember one  thing when we write try catch statement. try catch statement should be written in lowercase if we write in upper case  program will return error. the try block contains run able code and catch block contains the executable code  

Syntax:

  try
   {
  //Run some code here
   }
  catch(error)
  {
   //Handle errors here
  }
 


Example:
The coming exercise uses a try...catch statement. The example calls a function that retrieves a week name from an array based on the value passed to the function. If the value does not correspond to a week number (1-7), an exception is thrown with the value InvalidWeekNo and the statements in the catch block set the weekName variable to unknown.

<html>
<head>
<script language="javascript">
function getweekName (wo) {
wo=wo-1; // Adjust week number for array index (1=sunday, 7=Saturday)
var week=new Array("sunday","monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
if (week[wo] != null) {
return week[wo]
} else {
throw "InvalidweekNo"
}
}

try {
// statements to try
weekName=getweekName(myweek) // function could throw exception
}
catch (e) {
weekName="unknown"
//logMyErrors(e) // pass exception object to error handler
alert(e);
}
</script>
</head>
</body>
<html>

 

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 16, 2009

Ask Questions?    Discuss: Error Handling in Java Script   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
rahil
December 12, 2011
error

getting object error pls tell me how to clear it
DMCA.com