在 JavaScript 中,有7個錯誤物件,它們根據錯誤類型在 try/catch 表達式中引發:
ErrorEvalErrorRangeErrorReferenceErrorSyntaxErrorTypeErrorURIError
讓我們分析每個錯誤物件。
Error
這是一個通用的錯誤,所有其他錯誤物件都繼承自它。你永遠不會直接看到 Error 的實例,而是 JavaScript 會引發列在上面的其他錯誤之一,這些錯誤繼承自 Error。
它包含兩個屬性:
message:錯誤描述,一個可讓人理解的訊息,解釋發生了哪種錯誤name:錯誤類型(具體錯誤物件的名稱,例如TypeError或SyntaxError)
它只提供一個方法 toString(),負責將錯誤轉換為有意義的字串,可用於將其顯示在螢幕上。
EvalError
這種錯誤在現代 JavaScript 中已被定義,但實際上從未由 JavaScript 拋出,僅僅是出於相容性的目的而保留。它在 ECMAScript 3 中被定義,但在 ECMAScript 5.1 中的標準中已經不存在了。
它用於指示全域函數 eval() 的使用方式不正確,與其定義不兼容。
RangeError
當數字值不在其允許值的範圍內時,會引發 RangeError 錯誤。
最簡單的例子是將陣列長度設置為負值:
[].length = -1 //RangeError: Invalid array length
或者將其設置為大於 4294967295 的數字:
[].length = 4294967295 //4294967295
[].length = 4294967296 //RangeError: Invalid array length
(此魔術數字在 JavaScript 規範中被指定為32位無符號整數的最大範圍,相當於 Math.pow(2, 32) - 1)
以下是在實務中可能遇到的最常見的範圍錯誤:
RangeError: argument is not a valid code pointRangeError: invalid array lengthRangeError: invalid dateRangeError: precision is out of rangeRangeError: radix must be an integerRangeError: repeat count must be less than infinityRangeError: repeat count must be non-negative
ReferenceError
ReferenceError 指示檢測到無效的引用。一個 JavaScript 程序試圖讀取不存在的變量。
dog //ReferenceError: dog is not defined
dog = 2 //ReferenceError: dog is not defined
需要注意的是,如果不在嚴格模式下運行,上述語句將在全域對象上創建一個 dog 變量。
以下是在實務中可能遇到的最常見的引用錯誤:
ReferenceError: "x" is not definedReferenceError: assignment to undeclared variable "x"ReferenceError: can't access lexical declaration 'X' before initializationReferenceError: deprecated caller or arguments usageReferenceError: invalid assignment left-hand sideReferenceError: reference to undefined property "x"
SyntaxError
在程式中發現語法錯誤時會引發 SyntaxError。
以下是一些會產生語法錯誤的程式碼示例。
沒有名字的函式語句:
function() {
return 'Hi!'
}
//SyntaxError: function statement requires a name
在物件屬性定義後缺少逗號:
const dog = {
name: 'Roger'
age: 5
}
//SyntaxError: missing } after property list
以下是你可能在實務中遇到的最常見的語法錯誤:
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecatedSyntaxError: "use strict" not allowed in function with non-simple parametersSyntaxError: "x" is a reserved identifierSyntaxError: JSON.parse: bad parsingSyntaxError: Malformed formal parameterSyntaxError: Unexpected tokenSyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# insteadSyntaxError: a declaration in the head of a for-of loop can't have an initializerSyntaxError: function statement requires a nameSyntaxError: identifier starts immediately after numeric literalSyntaxError: illegal characterSyntaxError: invalid regular expression flag "x"SyntaxError: missing ) after argument listSyntaxError: missing ) after conditionSyntaxError: missing : after property idSyntaxError: missing ; before statementSyntaxError: missing = in const declarationSyntaxError: missing \] after element listSyntaxError: missing formal parameterSyntaxError: missing name after . operatorSyntaxError: missing variable nameSyntaxError: missing } after function bodySyntaxError: missing } after property listSyntaxError: redeclaration of formal parameter "x"SyntaxError: return not in functionSyntaxError: test for equality (==) mistyped as assignment (=)?SyntaxError: unterminated string literal
TypeError
TypeError 發生在一個值的類型與預期類型不同的情況下。
最簡單的例子是嘗試調用一個數字:
1() //TypeError: 1 is not a function
以下是你可能在實務中遇到的最常見的類型錯誤:
TypeError: "x" has no propertiesTypeError: "x" is (not) "y"TypeError: "x" is not a constructorTypeError: "x" is not a functionTypeError: "x" is not a non-null objectTypeError: "x" is read-onlyTypeError: 'x' is not iterableTypeError: More arguments neededTypeError: Reduce of empty array with no initial valueTypeError: can't access dead objectTypeError: can't access property "x" of "y"TypeError: can't define property "x": "obj" is not extensibleTypeError: can't delete non-configurable array elementTypeError: can't redefine non-configurable property "x"TypeError: cannot use 'in' operator to search for 'x' in 'y'TypeError: cyclic object valueTypeError: invalid 'instanceof' operand 'x'TypeError: invalid Array.prototype.sort argumentTypeError: invalid argumentsTypeError: invalid assignment to const "x"TypeError: property "x" is non-configurable and can't be deletedTypeError: setting getter-only property "x"TypeError: variable "x" redeclares argument
URIError
此錯誤是在調用使用 URI 的全局函數時引發的,例如:
decodeURI()decodeURIComponent()encodeURI()encodeURIComponent()
並傳遞一個無效的 URI。