JavaScript By Example

106 23
There are a number of different error objects available in JavaScript. Error is the most generic one but other more specific error objects exist - EvalError, RangeError, ReferenceError, SyntaxError, TypeError, and URIError all provide error processing for more specific types of errors.

In this example we look at how we can throw one of these more specific errors to produce an error message if an attempt is made to reference an entry outside the range of an array (a situation that would not normally produce a range error when trying to read from an array) or where the position specified isn't even a number.


getEntry = function(ary, pos){
  if (isNaN(pos)){
    throw new TypeError("getEntry position must be a number");
  if (pos >= ary.length || pos < 0){
    throw new RangeError("getEntry position specified is outside the array");
  return ary[pos];
}

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.