How to Use Try, Catch, Throw in JavaScript Sample Logic

Here is sample JavaScript logic. Here you can handle exceptions using Try, Catch and Throw.

JavaScript Code

< 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.

else {
// This statement throws an error
// directly to the catch block.

throw“ InvalidMonthNumber”

Try and Catch Block

// 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(“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.)


Related Posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.