文章出自個人博客https://knightyun.github.io/2019/09/02/js-try,轉載請申明。
程序在運行中難免遇到 bug,所以就需要好的調試手段找出問題所在,try, catch, throw
便是 JavaScript 中用來調試並對錯誤執行相關操作的工具,下面具體介紹其用法;
try, catch
基本語法結構:
try {
// ...
// 這裏寫需要調試的代碼段
} catch(error) {
// ...
// 這裏寫要對獲取的錯誤信息執行的操作
}
舉例:
try {
// 這裏故意寫錯函數名,爲了拋出錯誤
console.logg('This is an error and will not display');
} catch (e) {
console.log(e); // TypeError: console.logg is not a function
console.log(e.message); // console.logg is not a function
console.log(e.name); // TypeError
console.log(e.stack); // TypeError: console.logg is not a function
}
上面的錯誤代碼如果直接在正常環境中執行,便會直接在後臺輸出錯誤:
TypeError: console.loggg is not a function
但是使用 try, catch
結構的話,就可以獲取一個包含錯誤信息的對象,其包含各個部分的錯誤信息,便於進行一些自定義操作;
throw
throw
是在上述結構中使用的一個函數,接受一個參數作爲輸出信息,throw 的作用是中斷後面所有語句的執行,包括錯誤源,但是它前面的語句都會正常執行,它可以用於判斷錯誤的具體位置,例如:
try {
console.log('This will display.');
throw('My error position.'); // throw 將會中斷語句的執行
// 同樣故意製造錯誤
console.logg('This is an error and will not display.');
// 後面是正常語句
console.log('This will not display, either.')
} catch (e) {
console.log(e);
}
// This will display.
// My error position.
如果錯誤發生在 throw
語句之前的話,錯誤便會被正常拋出,而 throw
傳遞的信息不會被輸出,例如:
try {
console.logg('This is an error and wil not display.');
throw('My error position.');
// 後面的執行同樣會被中斷
console.log('This will not display, either.')
} catch(e) {
console.log(e);
}
// TypeError: console.logg is not a function.
因此,在調試過程中可以結合上面兩種情況,一步步找出錯誤的具體位置;