Below is the sample JavaScript logic. I have explained best practices how to use Try, Catch and Throw.
Java Script Error Handling best Practices
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/javascript”> function getMonthName (monthNumber) { // JavaScript arrays begin with 0, not 1, so // subtract 1. monthNumber = monthNumber - 1 // Create an array and fill it with 12 values var months = new Array(“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”, “Aug”,”Sep”,”Oct”,”Nov”,”Dec”) // If the monthNumber passed in is somewhere // between 0 and 11, fine; return the corresponding // month name. if (months[monthNumber] != null) { return months[monthNumber] } // Otherwise, an exception occurred, so throw // an exception. 250 Part IV: Interacting with Users 21_576593 ch14.qxd 10/12/04 10:02 PM Page 250 else { // This statement throws an error // directly to the catch block. throw “InvalidMonthNumber” } } ////////////////////////////////////////////////////// // The try block wraps around the main JavaScript // processing code. Any JavaScript statement inside // the try block that generates an exception will // automatically throw that exception to the // exception handling code in the catch block. ////////////////////////////////////////////////////// // The try block try { // Call the getMonthName() function with an // invalid month # (there is no 13th month!) // and see what happens. alert(getMonthName(13)) alert(“We never get here if an exception is thrown.”) } // The catch block catch (error) { alert(“An “ + error + “ exception was encountered. Please contact the program vendor.”) // In a real-life situation, you might want // to include error-handling code here that // examines the exception and gives users specific // information (or even tries to fix the problem, // if possible.) }
Keep Reading