catch: 只有try里面的代碼塊發生錯誤時,才會執行這里的代碼,參數err記錄著try里面代碼的錯誤信息
finally: 無論有無異常里面代碼都會執行
try{ console.log(0); }catch (err){ console.log(1); console.log(hello); }finally { console.log(2); } //最后結果分別打印出 0 2 /* try{ a.b.c(); }catch (e){ console.log(1); console.log(hello); }finally { console.log(2); } */ //最后結果分別打印出 1 2 報錯:hello is not defined /* try{ a.b.c(); }catch (e){ console.log(1); try{ console.log(hello); }catch (e){ console.log(3); } }finally { console.log(2); console.log(word); } */ //最后結果分別打印出 1 3 2 報錯:word is not defined /* try{ a.b.c(); }catch (e){ console.log(1); console.log(hello); }finally { console.log(2); console.log(word); }*/ //最后結果分別打印出 1 2 報錯:word is not defined
總結:
try里面的代碼報錯的時候,catch里面的代碼才會執行,finally里面的代碼永遠會執行
catch和finally里面,正常的代碼會從上到下順序執行
如果只是catch里面代碼出錯,則報catch里面的錯誤
如果catch和finally都出錯則會報finally里面的錯誤
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com