RangeError - JavaScript 编辑
The RangeError
object indicates an error when a value is not in the set or range of allowed values.
Description
A RangeError
is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.
This can be encountered when:
- passing a value that is not one of the allowed string values to
String.prototype.normalize()
, or - when attempting to create an array of an illegal length with the
Array
constructor, or - when passing bad values to the numeric methods
Number.prototype.toExponential()
,Number.prototype.toFixed()
orNumber.prototype.toPrecision()
.
Constructor
RangeError()
- Creates a new
RangeError
object.
Instance properties
RangeError.prototype.message
- Error message. Although ECMA-262 specifies that
RangeError
should provide its ownmessage
property, in SpiderMonkey, it inheritsError.prototype.message
. RangeError.prototype.name
- Error name. Inherited from
Error
. RangeError.prototype.fileName
- Path to file that raised this error. Inherited from
Error
. RangeError.prototype.lineNumber
- Line number in file that raised this error. Inherited from
Error
. RangeError.prototype.columnNumber
- Column number in line that raised this error. Inherited from
Error
. RangeError.prototype.stack
- Stack trace. Inherited from
Error
.
Examples
Using RangeError (for numeric values)
function check(n)
{
if( !(n >= -500 && n <= 500) )
{
throw new RangeError("The argument must be between -500 and 500.")
}
}
try
{
check(2000)
}
catch(error)
{
if (error instanceof RangeError)
{
// Handle the error
}
}
Using RangeError (for non-numeric values)
function check(value)
{
if(["apple", "banana", "carrot"].includes(value) === false)
{
throw new RangeError('The argument must be an "apple", "banana", or "carrot".')
}
}
try
{
check("cabbage")
}
catch(error)
{
if(error instanceof RangeError)
{
// Handle the error
}
}
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'RangeError' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论