views:

66

answers:

1

Hi all, 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.

+1  A: 

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.

Techpriester
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/TypeError
DjangoRocks