Javascript throw statement

Introduction

Throwing an Error


function OptionalArgument(param){
   try{//from  w w w . j a  v  a  2s.  c  o  m
      // Determine whether there were any params passed.
      if (arguments.length == 0){
         throw new ReferenceError("No Data Supplied");
      }
      var Result = new String();
      for (var i = 0; i < arguments.length; i++){
         if (typeof(arguments[i]) != 'string'){
            throw TypeError(
               "Incorrect Data Supplied, type:" +
               typeof(arguments[i]) + " value: " +
               arguments[i]);
         }
         Result += arguments[i] + "<br />";
      }
   }catch(Err)
   {
      console.log(Err.name + "<br />" + Err.message);
      return;
   }
   
   console.log(Result);
}
OptionalArgument();
OptionalArgument('Red');
OptionalArgument('Red', 'Green', 'Blue');
OptionalArgument('Red', 0, true, 'Orange');
function doWork () {
  // throw error that say 'unable to do work'
  throw new Error('unable to do work');
}

try{//from   w  w w.ja va2  s.c om
  //call do work
  doWork();
// throw new Error('Unable to do the thing you wanted!');

} catch (e) {
  console.log(e.message);
} finally {
  console.log('Finally block executed!');
}

console.log('try catch ended');



PreviousNext

Related