当前位置: 首页 > 后端技术 > PHP

try-catch-finally,你忽略的执行顺序

时间:2023-03-29 22:48:49 PHP

try-catch是捕捉异常的神器,无论是调试还是防止软件崩溃,都离不开它。今天介绍finally添加后的执行顺序functiontest(){try{console.log(1);}最后{console.log(2);}}console.log(测试());//12嗯!按顺序执行。我们添加一个return语句来尝试functiontest(){try{console.log(1);返回'??from_try';}catch(e){//TODO}finally{console.log(2);}}控制台日志(测试());//12from_try等等,不应该是1>from_try>2的顺序吗?对不起,是这样的。在try和catch的代码块中,如果遇到return语句,在return之前会先执行finally中的内容,所以会比from_try先输出2。我们还在finallyfunctiontest(){try{console.log(1);中添加了一个return语句;返回'??from_try';}catch(e){//TODO}finally{console.log(2);返回'??from_finally';}}console.log(测试());//12from_finally买了Karma,为什么我的from_try不见了?不好意思,按照前面的规则,finally会先执行,所以如果finally里面有return语句,那就真的是return了。现在作者故意在try语句块中报错functiontest(){try{console.log(1);抛出新错误(“抛出”);}catch(e){console.log(e.message);返回“from_catch”;}最后{console.log(2);}}console.log(测试());//1throw2from_catch看来try和catch的返回需要先经过finally。你以为就这样结束了吗?让我们来展示一下函数action(){console.log(1);return'action';}functiontest(){尝试{returnaction();}catch(e){}finally{return'finally';}}console.log(测试());//1'finally'try和catch中return的值会先缓存起来,不会不执行。如果finally不返回,则直接返回缓存的值。结语只是一个小细节。但也希望各位评委好好利用这个特点。