若是代碼發生了錯誤,又沒有被try ... catch捕獲,那麼,程序執行流程會跳轉到哪呢?函數
function getLength(s) { return s.length; } function printLength() { console.log(getLength('abc')); // 3 console.log(getLength(null)); // Error! } printLength();
若是在一個函數內部發生了錯誤,它自身沒有捕獲,錯誤就會被拋到外層調用函數,若是外層函數也沒有捕獲,該錯誤會一直沿着函數調用鏈向上拋出,直到被JavaScript引擎捕獲,代碼終止執行。spa
因此,咱們沒必要在每個函數內部捕獲錯誤,只須要在合適的地方來個統一捕獲,一網打盡:code
'use strict'; function main(s) { console.log('BEGIN main()'); try { foo(s); } catch (e) { alert('出錯了:' + e); } console.log('END main()'); } function foo(s) { console.log('BEGIN foo()'); bar(s); console.log('END foo()'); } function bar(s) { console.log('BEGIN bar()'); console.log('length = ' + s.length); console.log('END bar()'); } main(null);
當bar()
函數傳入參數null
時,代碼會報錯,錯誤會向上拋給調用方foo()
函數,foo()
函數沒有try ... catch語句,因此錯誤繼續向上拋給調用方main()
函數,main()
函數有try ... catch語句,因此錯誤最終在main()
函數被處理了。blog
至於在哪些地方捕獲錯誤比較合適,須要視狀況而定。ip