Search code examples
javascriptexceptiontypeerrorreferenceerror

How do we throw and catch a RangeError, ReferenceError, TypeError in JavaScript?


I was wondering if any of you have tried catching errors such as RangeError, ReferenceError and TypeError using JavaScript's exception handling mechnism?

For instance for RangeError:

try {
var anArray = new Array(-1); 
// an array length must be positive

         throw new RangeError("must be positive!")
}
catch (error) {  
         alert(error.message);
         alert(error.name);
}
finally {
         alert("ok, all is done!");
}

In the above case, am i throwing a new RangeError object?

Cos my code example at alert(error.message) doesnt show the user defined message of "must be positive".

What can I do to throw my own RangeError object ( and ReferenceError, TypeError ) ?

Best.


Solution

  • This is almost a year old, but I figure better late than never. It depends on the browser, but in some instances (cough, cough, FIREfox, cough), RangeError inherits the Error object's message property instead of supplying it's own. I'm afraid the only workaround is to throw new Error("must be positive!"). Sorry.