最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

exception - How do we throw and catch a RangeError, ReferenceError, TypeError in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论