Error Handling in Java Script

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

Error Handling 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>