跳轉到內容

JavaScript/保留字/throw

來自華夏公益教科書,開放的書籍,面向開放的世界
上一頁:this 保留字 下一頁:throws

Thethrow關鍵字

[編輯 | 編輯原始碼]

Thethrow關鍵字用於確保在異常發生時捕獲異常。它有強制性的 catch 子句,以及可選的 finally 子句。如果 try 塊中的程式碼沒有導致異常,則 finally 塊中的程式碼將執行,如果存在。如果發生錯誤,則 catch 子句中的註釋將執行,finally 塊將執行,如果存在。

程式碼
  var result;

  try {
    result = log(-12.05);
    alert("Executed comment successfully.");
  } catch(err) {
    document.getElementById("demo").innerHTML = err.message;
	throw("An error occurred, and result could not be calculated!");
  } finally {
    alert("result = " + result); // This line will execute anyway
  }
(將丟擲帶有文字“發生錯誤,無法計算結果!”的異常。
result = undefined


另請參閱

[編輯 | 編輯原始碼]
上一頁:this 保留字 下一頁:throws
華夏公益教科書