前言自从ECMA-262第3版引入了try catch语句,作为JavaScript中处理异常的一种标准方式。基本的语法如下所示。一、try catch基本语法try { //可能会导致错误的代码} catch (error) { //在错误发生时怎么处理}finally { //即使报错始终执行 }二、try catch特点1.try catch耗性能1.1 try catch耗性能原理ECMAScript 2015 -The try Statement13.15.5 Static Semantics: VarDeclaredNamesTryStatement : try Block Catch Finally1.Let names be VarDeclaredNames of Block.2.Append to names the elements of the VarDeclaredNames of Catch.3.Append to names the elements of the VarDeclaredNames of Finally.4.Return names.13.15.6 Static Semantics: VarScopedDeclarationsTryStatement : try Block Catch Finally1.Let declarations be VarScopedDeclarations of Block.2.Append to declarations the elements of the VarScopedDeclarations of Catch.3.Append to declarations the elements of the VarScopedDeclarations of Finally.4.Return declarations.根据上面ECMAScript文档的13.15.5和13.15.6`。下面仅为本妹子自己的翻译理解,仅供参考上面大概说运行try catch时,需要将当前的词法环境和作用域全部分别添加到catch和Finally所要执行的代码块中。从上可以推断出try catch是消耗性能的。1.2 try catch耗性能实验下面我用Chrome62和IE9分别添加多个try catch,进行对比实验,虽然,很想抛弃万恶的IE,但是很多国内的产品不答应呀,除非我们去健身房再多练练,打一架,嘿嘿~~1.2.1 实验数据://没有加try catch(function () { var i = 0; i++;}())//有try catch(function () { var i = 0; try { i++; } catch (ex) { } finally { }}())1.2.2 实验结果:1.2.3 实验链接:https://jsperf.com/test-try-catch3https://jsperf.com/test-try-catch上面实验数据对比得知,try catch会消耗性能,但是try catch对Chrome的影响比IE11小很多,据说是V8引擎新的编译器TurboFan 起到的作用,有兴趣的小伙伴们可以看下v8_8h_source的3354行起,但是IE11是slower不少的。这就根据小伙伴们的业务对象了,如果只面向现代浏览器,try catch消耗性能影响会很小;如果需要兼容IE或内嵌在低端的webView时,可适当考虑下try catch消耗性能。2.try catch捕获不到异步错误尝试对异步方法进行try catch操作只能捕获当次事件循环内的异常,对callback执行时抛出的异常将无能为力。try { setTimeout(()=>{ const A = 1 A = 2 },0)} catch (err) { // 这里并不能捕获回调里面抛出的异常 console.log("—–catch error——") console.log(err)}异步情况想捕获异常,建议在异步函数里包一层try catch。setTimeout(() => { try { const A = 1 A = 2 } catch (err) { console.log(err) }}, 0)3.try catch抛出错误与 try-catch 语句相配的还有一个 throw 操作符,随时抛出自定义错误,可以根据不同错误类型,创建自定义错误消息。throw new Error(“Something bad happened.”);throw new SyntaxError(“I don’t like your syntax.”);throw new TypeError(“What type of variable do you take me for?”); throw new RangeError(“Sorry, you just don’t have the range.”);throw new EvalError(“That doesn’t evaluate.”);throw new URIError(“Uri, is that you?”);throw new ReferenceError(“You didn’t cite your references properly.”);如果觉得自定义的报错不合理,想看原生报错,可以使用Chrome的Pause on exceptions功能三、慎用try catchtry catch最适合处理那些我们无法控制的错误,如I/O操作等,后端nodeJs或java读取I/O操作比较多比如读数据库,所以用try catch比较多。前端可以用在上传图片、使用别人的js库报错、async await同步调接口等地方适用。async function f() { try { await Promise.reject(‘出错了’); } catch(e) { } return await Promise.resolve(‘hello world’);}但是大部分前端客户端代码处理都不怎么依赖环境也没有I/O操作,都是自己写的代码,在明明白白地知道自己的代码会发生错误时,再使用try catch语句就不太合适了,对应数据类型的错误,建议小伙伴们用解构赋值指定默认值、&&和||来规避,所以慎用try catch。foo = (obj = {}) => { let obj1 = result || {}; if (obj && obj.code) { console.log(‘obj.code’,obj.code) }}参考资料https://raoenhui.github.io/js/2018/12/16/tryCatchECMAScript 2015 -The try Statementhttps://developers.google.com/web/updates/2015/05/automatically-pause-on-any-exceptionhttps://v8docs.nodesource.com/node-0.8/d4/da0/v8_8h_source.htmlHappy coding .. :)