// JS错误信息类型1. SyntaxError 语法错误变量名不规范var 1 = 1;var 1ab = 1; // Uncaught SyntaxError: Invalid or unexpected token 未被标记的语法错误关键字赋值new = 5;基本的语法错误var a =5:2. ReferenceError 引用错误变量或者函数未被声明test();console.log(a);给无法被赋值的对象赋值的时候var a = 1 = 2;3. RangeError 范围错误数组长度赋值为负数arr.length= -1对象方法参数超出可行范围var num = new Number(66.66);console.log(num.toFixed(-1));4. TypeError 类型错误调用不存在的方法123();var obj = {};obj.say(); //把say认为是一个属性实例化原始值var a = new 'string'; // 'string' is not a constructor5. URIError URI错误URI: UNIFORM RESOURCE IDENTIFIER 统一资源标识符URL: UNIFORM RESOURCE LOCATOR 统一资源定位符URN: UNIFORM RESOURCE NAME 统一资源名称URL:http://www.baidu.com/news#today ftp://www.baidu.com/ftp#developerURN: www.baidu.com/ftp#develper -> ID 指代资源唯一id href="tel:1249343443" 也是URNvar myUrl = 'http://www.baidu.cn?name='张三';var newUrl = encodeURI(myUrl); 中文转为中文字符编码var newUrl = decodeURI(myUrl); 中文字符编码转为中文var str = decodeURI('%fdssf%') // 报错 URIError URI错误6. EvalError eval函数执行错误eval把JSON字符串转为JSON对象7. 自定义错误var error = new SyntaxError('代码错误');console.log(error)
try catch
系统自动为我们抛出错误手动抛出错误的方法try catch finally throwtry{ console.log('正常执行1'); console.log(a); // 执行报错 console.log('正常执行2'); // 不执行}catch(e){ console.log(e); // catch 捕获try中的错误 ,没有错误不走catch // e对象 e.name 错误类型 e.message 错误信息} finally { console.log('正常执行3'); // 无论报 不报错一定执行}console.log('正常执行4');try{ if(jsonStr === '') { throw 'JSON字符串为空' // 自定义错误 } var json = JSON.parse(jsonStr);} catch(e) { var errorTip = { name: '数据传输失败', errorCode: '10010' }}
ES5 严格模式