Share via


throw 陳述式

更新:2007 年 11 月

產生一個 try...catch...finally 陳述式可處理的錯誤條件。

 throw [exception]

引數

  • exception
    選擇項。任何運算式。

備註

使用 throw 陳述式時可以不加上引數,除非 throw 陳述式是包含在 catch 區塊內。若是如此,throw 陳述式會重新擲回封閉的 catch 陳述式攔截到的錯誤。當提供引數時,throw 陳述式會產生 exception 的值。

範例

下列範例會根據傳入值擲回錯誤,然後說明如何在 try...catch...finally 陳述式的階層架構中處理該錯誤:

function TryCatchDemo(x){
   try {
      try {
      if (x == 0)                            // Evalute argument.
         throw "x equals zero";              // Throw an error.
      else
         throw "x does not equal zero";      // Throw a different error.
      }
      catch(e) {                             // Handle "x=0" errors here.
         if (e == "x equals zero")           // Check for a handled error.
            return(e + " handled locally."); // Return error message.
         else                                // Can't handle error here.
            throw e;                         // Rethrow the error for next
      }                                      // error handler.
   }
   catch(e) {                                // Handle other errors here.
      return(e + " error handled higher up."); // Return error message.
   }
}
print(TryCatchDemo(0)+ "\n");
print(TryCatchDemo(1));

需求

5 版

請參閱

參考

try...catch...finally 陳述式

Error 物件