3

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Actually, array indices in JavaScript don't need to be positive since arrays are essentially hash tables here. If you try to access a non-existing key in an array, the result will simply be undefined.

You can catch that with a simple condition:

if (typeof someArray[foo] !== "undefined") {
    //do stuff
} else {
    //do error handling
    //Here I'm just throwing a simple exception with nothing than a message in it.
    throw new Error('something bad happened');
}

I'm not sure what you mean by "TypeError", though. Please give some more detail.

2 Comments

Just stumbeld upon this, and I have to correct you: new Array(-1) IS invalid. While you are correct about indices not having to be positive, the first argument of the Array constructor is the number of elements inside the array after creation (all default to undefined) and defaults to zero. Obviously you cannot create an array with less than 0 elements in it. (Also not that using negative indices in Javascript arrays will not adjust the length property, as it indicates the highest positive index that has been used. This is why it does make sense in most cases to not allow them)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.