天天看點

js常見錯誤類型

(1)SyntaxError

SyntaxError是解析代碼時發生的文法錯誤

// 變量名錯誤 

var 1a; 

// 缺少括号 

console.log 'hello');

(2)ReferenceError

ReferenceError是引用一個不存在的變量時發生的錯誤。

unknownVariable 

// ReferenceError: unknownVariable is not defined

另一種觸發場景是,将一個值配置設定給無法配置設定的對象,比如對函數的運作結果或者this指派。

console.log() = 1 

// ReferenceError: Invalid left-hand side in assignment 

this = 1 

// ReferenceError: Invalid left-hand side in assignment

上面代碼對函數console.log的運作結果和this指派,結果都引發了ReferenceError錯誤

(3)RangeError

RangeError是當一個值超出有效範圍時發生的錯誤。主要有幾種情況,一是數組長度為負數,二是Number對象的方法參數超出範圍,以及函數堆棧超過最大值。

new Array(-1) 

// RangeError: Invalid array length 

(1234).toExponential(21) 

// RangeError: toExponential() argument must be between 0 and 20

(4)TypeError

TypeError是變量或參數不是預期類型時發生的錯誤。比如,對字元串、布爾值、數值等原始類型的值使用new指令,就會抛出這種錯誤,因為new指令的參數應該是一個構造函數。

new 123 

//TypeError: number is not a func 

var obj = {}; obj.unknownMethod() 

// TypeError: undefined is not a function

上面代碼的第二種情況,調用對象不存在的方法,會抛出TypeError錯誤。

(5)URIError

URIError是URI相關函數的參數不正确時抛出的錯誤,主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()這六個函數。

decodeURI('%2') 

// URIError: URI malformed

(6)EvalError

eval函數沒有被正确執行時,會抛出EvalError錯誤。該錯誤類型已經不再在ES5中出現了,隻是為了保證與以前代碼相容,才繼續保留。

以上這6種派生錯誤,連同原始的Error對象,都是構造函數。開發者可以使用它們,人為生成錯誤對象的執行個體。

new Error("出錯了!");

new RangeError("出錯了,變量超出有效範圍!");

new TypeError("出錯了,變量類型無效!");

上面代碼表示建立錯誤對象的執行個體,實質就是手動抛出錯誤。可以看到,錯誤對象的構造函數接受一個參數,代表錯誤提示資訊(message)。

繼續閱讀