JavaScript六种错误类型
处理代码错误的核心,首先要知道代码里面会发生什么错误
JavaScript错误类型:
- SyntaxError(语法错误)
- ReferenceError(引用错误)
- RangeError(范围错误)
- TypeError(类型错误)
- URLError(URL错误)
- EvalError(eval错误)
SyntaxError(语法错误)
解释代码时发生的语法错误
var 1a; // 语法错误,javascript变量首位字符,必须是字母或者下划线
// Uncaught SyntaxError: Invalid or unexpected token
var delete = 1; // 语法错误,javascript变量名不能是保留字段
// Uncaught SyntaxError: Unexpected token 'delete'
ReferenceError(引用错误)
// 引用了一个不存在的变量
function foo(a) {
return a + b;
}
foo(2)
/*
Uncaught ReferenceError: b is not defined
at foo (<anonymous>:2:12)
at <anonymous>:4:1
*/
RangeError(范围错误)
new Date('2014-25-23').toISOString();
/*
Uncaught RangeError: Invalid time value
at Date.toISOString (<anonymous>)
at <anonymous>:1:24
*/
TypeError(类型错误)
undefined.bar; // // 错误类型: undefined没有这个属性
/*
Uncaught TypeError: Cannot read property 'bar' of undefined
at <anonymous>:1:11
*/
URLError(URL错误)
decodeURIComponent('%');
/*
Uncaught URIError: URI malformed
at decodeURIComponent (<anonymous>)
at <anonymous>:1:1
*/
EvalError(eval错误)
throw new EvalError('Hello', 'someFile.js', 10);
/*
Uncaught EvalError: Hello
at <anonymous>:1:9
*/