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.
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.
Share Improve this question asked Jul 23, 2010 at 8:22 DjangoRocksDjangoRocks 14.2k7 gold badges38 silver badges52 bronze badges2 Answers
Reset to default 2This 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.
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.