異常處理

開放

10.1 try...catch 區塊

異常處理是編程中的一個重要方面,它有助於提高代碼的穩定性和可靠性。在 JavaScript 中,異常處理使用關鍵字 trycatchfinallythrow。 在這節課中,我們將討論這些關鍵字,包含它們的語法和使用範例。

1. try...catch 區塊

try...catch 構造用於處理在 try 區塊中發生的錯誤。如果在 try 區塊中發生錯誤,控制會轉移到 catch 區塊,這裡可以處理該錯誤。

語法:

try {
  // 可能會引發異常的代碼
} catch (error) {
  // 處理異常的代碼
}

在這個範例中,雖然除以零不會在 JavaScript 中引發錯誤,但如果是其他錯誤(例如訪問未定義的變量),catch 區塊將會處理:

JavaScript
try {
  let result = 10 / 0;

  console.log(result);

} catch (error) {
  console.error('An error occurred:', error);
}

10.2. finally 區塊

finally 區塊用於執行不論在 try 區塊中是否出現異常都必須執行的代碼。finally 區塊位於 catch 區塊之後。

語法:

try {
  // 可能會引發異常的代碼
} catch (error) {
  // 處理異常的代碼
} finally {
  // 始終會執行的代碼
}

在這個範例中,This will always execute. 消息將無論是否發生錯誤都會被輸出:

JavaScript
try {
  let result = 10 / 0;
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error);
} finally {
  console.log('This will always execute.');
}

10.3 throw 操作符

操作符 throw 用於顯式拋出異常。使用它可以拋出自定義錯誤。

語法:

throw expression;

其中:

  • expression: 任何將被拋出為異常的表達式或對象

使用範例

在這個範例中,如果嘗試除以零,將拋出一個錯誤,並由 catch 區塊進行處理:

JavaScript
function divide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero is not allowed.');
  }
  return a / b;
}

try {
  let result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}

10.4 進階範例和應用

範例 1: 多重異常

有時在 try 區塊中會出現不同類型的錯誤。你可以使用錯誤對象的屬性來對它們進行不同處理。

在這個範例中,我們只對 JSON 語法錯誤進行單獨處理,其他可能的錯誤則進行另一種處理:

JavaScript
try {
  JSON.parse('{ malformed JSON string }');
} catch (error) {
  if (error instanceof SyntaxError) {
    console.error('JSON Syntax Error:', error.message);
  } else {
    console.error('Unexpected Error:', error);
  }
} finally {
  console.log('Parsing attempt finished.');
}

範例 2: 嵌套的 try...catch 區塊

可以使用嵌套的 try...catch 區塊來更精細地處理錯誤。

在這個範例中,第一次 try 區塊中發生的錯誤將由內部 catch 區塊處理, 然後重新拋出,以便由外部 catch 區塊進行處理:

JavaScript
try {
  try {
    let result = divide(10, 0);
    console.log(result);
  } catch (innerError) {
    console.error('Inner catch:', innerError.message);
    throw innerError;
  }
} catch (outerError) {
  console.error('Outer catch:', outerError.message);
} finally {
  console.log('Nested try...catch finished.');
}

function divide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero is not allowed.');
  }
  return a / b;
}

範例 3: 使用 finally 釋放資源

finally 區塊對於釋放資源很有用,例如關閉文件或完成網絡連接。

在這個範例中,無論文件在讀取時是否出現錯誤,文件都將始終被關閉:

JavaScript
function readFile(filePath) {
  let file;
  try {
    file = openFile(filePath); // 打開文件的函數
    // 工作於文件
  } catch (error) {
    console.error('Error reading file:', error.message);
  } finally {
    if (file) {
      closeFile(file); // 關閉文件的函數
    }
    console.log('File processing finished.');
  }
}

function openFile(path) {
  // 打開文件的邏輯
}

function closeFile(file) {
  // 關閉文件的邏輯
}

readFile('path/to/file.txt');

使用 trycatchfinallythrow 進行 JavaScript 異常處理 能創建更可靠和健壯的應用程序。理解和正確使用這些結構有助於有效管理錯誤,釋放資源,並改善用戶體驗。

1
任務
Frontend SELF TW,  等級 36課堂 4
上鎖
錯誤處理
錯誤處理
1
任務
Frontend SELF TW,  等級 36課堂 4
上鎖
finally 區塊
finally 區塊
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言