JavaScript 中的錯誤處理

JavaScript 中的錯誤處理

本文說明了在 JavaScript 中如何進行錯誤處理。

YouTube Video

JavaScript 中的錯誤處理

JavaScript 中的錯誤處理是捕捉並適當處理程式遇到意外問題時的重要特性。通常使用 try...catch 語法來捕捉和處理錯誤。此外,在處理 Promise 或非同步操作時,也可以使用 async/awaitPromise.prototype.catch 進行錯誤處理。

try...catch 語法

try...catch 用於在代碼塊中捕捉並處理錯誤。

 1try {
 2    // Code that may throw an error
 3    let result = riskyFunction();
 4    console.log(result);
 5} catch (error) {
 6    // Catch and handle the error
 7    console.error("An error occurred:", error.message);
 8} finally {
 9    // Code that will always execute
10    console.log("Error handling has completed.");
11}
  • 如果在 try 塊內發生錯誤,程式執行將中斷,並執行 catch 塊。
  • finally 塊總會執行,不論是否發生錯誤。這對於釋放資源和進行最終處理等操作十分有用。

拋出錯誤 (throw)

在 JavaScript 中,可以使用關鍵字 throw 顯式觸發錯誤。用於拋出自定義錯誤訊息或自定義錯誤。

 1function checkAge(age) {
 2    if (age < 18) {
 3        throw new Error("You are under 18 years old.");
 4    }
 5    return "Age verification completed.";
 6}
 7
 8try {
 9    let result = checkAge(15);
10    console.log(result);
11} catch (error) {
12    console.error(error.message);  // Displays "You are under 18 years old."
13}

非同步操作中的錯誤處理 (Promiseasync/await)

在執行非同步操作時,錯誤處理略有不同。使用 Promise 時,可以通過 catch 方法捕捉錯誤。

1let promise = new Promise((resolve, reject) => {
2    // Asynchronous operation
3    setTimeout(() => reject(new Error("An issue has occurred!")), 1000);
4});
5
6promise
7    .then(result => console.log(result))
8    .catch(error => console.error(error.message));  // Displays "An issue has occurred!"

使用 async/await 執行非同步操作時,可以通過 try...catch 處理錯誤。

 1async function fetchData() {
 2    try {
 3        let response = await fetch('https://api.example.com/data');
 4        let data = await response.json();
 5        console.log(data);
 6    } catch (error) {
 7        console.error("An error occurred while fetching data:", error.message);
 8    }
 9}
10
11fetchData();

總結

  • 可以使用 try...catch 語法捕捉同步錯誤。
  • 可以使用 throw 拋出自定義錯誤。
  • 非同步操作中的錯誤可以通過 Promisecatch 方法,或使用 async/awaittry...catch 處理。

通過使用這些方法,可以確保程式即使在發生錯誤時也能正常運行。

Error

Error 類用於錯誤處理。它提供了創建錯誤並提供錯誤訊息和堆棧追踪的功能。

1try {
2    throw new Error("Something went wrong");
3} catch (e) {
4    console.log(e.message); // Something went wrong
5}

基本用法

當發生錯誤時,可以顯式地創建一個 Error 對象。可以使用 new Error() 創建一個實例並傳遞一個錯誤訊息。

1const error = new Error("Something went wrong");
2console.log(error.message);  // "Something went wrong"
3console.log(error.name);     // "Error"
4
5// Stack trace (information about where the error occurred)
6console.log(error.stack);

Error 物件的屬性

Error 物件擁有以下屬性。

  • message:這是錯誤訊息。
  • name:錯誤的名稱,預設值為 "Error"
  • stack:包含錯誤發生位置的堆疊追蹤,對除錯非常有用。

使用 throw 丟出錯誤

在 JavaScript 中,可以使用關鍵字 throw 丟出錯誤。這用於在特定情況下中斷處理並將控制權傳遞給錯誤處理程式。

1function doSomething() {
2    throw new Error("This function is not yet implemented");
3}
4
5try {
6    doSomething();
7} catch (e) {
8    console.error(e.message);  // "This function is not yet implemented"
9}

使用 throw 丟出的錯誤可以通過 try...catch 語法捕獲。

創建自定義錯誤

在 JavaScript 中,可以通過擴展 Error 類來創建自定義錯誤。這使您能够創建針對特定情況的錯誤。

 1class CustomError extends Error {
 2    constructor(message) {
 3        super(message);  // Call the parent class constructor
 4        this.name = "CustomError";  // Set the error name
 5    }
 6}
 7
 8try {
 9    throw new CustomError("A custom error has occurred");
10} catch (e) {
11    console.error(e.name);    // "CustomError"
12    console.error(e.message); // "A custom error has occurred"
13}

內建錯誤類別

JavaScript 擁有幾個擴展自 Error 類的內建錯誤類別。這些用來表示特定的錯誤。

  • ReferenceError:當引用不存在的變量時發生。
  • TypeError:當值的類型與預期類型不符時發生。
  • RangeError:當數值超出允許範圍時發生。
  • SyntaxError:當執行語法不正確的程式碼時發生。
  • EvalError:與 eval() 函數使用相關的錯誤。現今很少使用。
  • URIError:當使用無效的 URI(編碼或解碼錯誤)時發生。
範例:ReferenceError

以下是一個 ReferenceError 的例子。

1try {
2    console.log(undefinedVariable);  // Undefined variable
3} catch (e) {
4    console.error(e.name);    // "ReferenceError"
5    console.error(e.message); // "undefinedVariable is not defined"
6}
範例:TypeError

以下是一個 TypeError 的例子。

1try {
2    null.f();  // Attempting to call a function on null
3} catch (e) {
4    console.error(e.name);    // "TypeError"
5    console.error(e.message); // "Cannot read properties of null (reading 'f')"
6}

finally 區塊

try...catch 語法中,可使用 finally 區塊執行無論是否發生錯誤都需要執行的操作。

1try {
2    throw new Error("An issue has occurred");
3} catch (e) {
4    console.error(e.message);  // "An issue has occurred"
5} finally {
6    console.log("Performing cleanup");
7}

在此範例中,即使發生錯誤,finally 區塊中的操作仍然會被執行。

例外處理的優點

透過正確實現錯誤處理,您可以防止應用程式在發生意外行為時崩潰。透過適當使用 try...catch 語法和錯誤物件,您可以撰寫出更穩健的程式碼。

 1function divide(a, b) {
 2    if (b === 0) {
 3        throw new Error("Cannot divide by zero");
 4    }
 5    return a / b;
 6}
 7
 8try {
 9    console.log(divide(4, 0));  // An error will occur
10} catch (e) {
11    console.error(e.message);   // "Cannot divide by zero"
12}

總結

  • Error 類別用於表示錯誤原因並執行錯誤處理。
  • 使用 try...catch...finally 語法來處理錯誤,並防止應用程式意外終止。
  • 您也可以擴展 Error 類別來創建自定義錯誤。
  • 您可以透過使用內建的錯誤類別(如 TypeErrorReferenceError),來處理各種類型的錯誤。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video