当前位置: 首页 > Web前端 > JavaScript

try、catch、finally使用注意事项

时间:2023-03-27 11:29:39 JavaScript

使用try、catch、finally的注意事项中的代码依然会继续执行  3、如果try或catch中有return语句,finally中的表达式还是会执行,但是try.catchreturn的值不受影响。finally语句的执行不会影响try或catch的returnconsttest=()=>{leta=123;try{console.log('这是-try-,a=',a);返回一个;}catch(error){console.log('这是-catch-,a=',a);返回一个;}finally{console.log('这是-finally-,a=',a);一='000';console.log('这是结束-最后-,a=',a);}};控制台日志(测试());打印结果//thisis-try-,a=123//thisis-finally-,a=123//thisisendof-finally-,a=000//123exceptioncatchconsttest=()=>{让一个=123;try{console.log('这是-try-,a=',a);thrownewError('测试错误');返回一个;}赶上(错误){a=9999;console.log('这是-catch-,a=',a);返回一个;}最后{a='000';console.log('这是-最后-,a=',a);}};控制台日志(测试());打印结果//这是-尝试-,a=123//thisis-catch-,a=9999//thisis-finally-,a=000//9999这里要注意返回的不是引用类型。引用类型,finally的修改会影响函数的返回值4.finally代码中最好不要包含return,这样会覆盖掉try和catch的returnconsttest=()=>{leta=123;try{console.log('这是-try-,a=',a);thrownewError('测试错误');返回一个;}catch(error){console.log('这是-catch-,a=',a);=9999;返回一个;}finally{console.log('这是-finally-,a=',a);一='000';console.log('这是结束-最后-,a=',a);返回一个;}};控制台日志(测试());打印结果//thisis-try-,a=123//thisis-catch-,a=123//thisis-finally-,a=9999//thisisendof-finally-,a=000//000