共用方式為


關於擲回

簡短描述

描述可產生終止錯誤的 Throw 關鍵字。

詳細描述

Throw 關鍵詞會導致終止錯誤。 您可以使用 Throw 關鍵詞來停止命令、函式或腳本的處理。

例如,您可以在 If 語句的腳本區塊中使用 Throw 關鍵詞來響應條件或 Try-Catch-Finally 語句的 Catch 區塊。 您也可以在參數宣告中使用 Throw 關鍵詞來強制函式參數。

Throw 關鍵詞可以擲回任何物件,例如使用者訊息字串或造成錯誤的物件。

SYNTAX

Throw 關鍵詞的語法如下所示:

throw [<expression>]

Throw 語法中的表達式是選擇性的。 當 Throw 語句未出現在 Catch 區塊中,而且不包含表示式時,會產生 ScriptHalted 錯誤。

C:\PS> throw

ScriptHalted
At line:1 char:6
+ throw <<<<
+ CategoryInfo          : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted

如果在沒有表達式的 Catch 區塊中使用 Throw 關鍵詞,則會再次擲回目前的 RuntimeException。 如需詳細資訊,請參閱about_Try_Catch_Finally。

擲回字串

Throw 語句中的選擇性表達式可以是字串,如下列範例所示:

C:\PS> throw "This is an error."

This is an error.
At line:1 char:6
+ throw <<<<  "This is an error."
+ CategoryInfo          : OperationStopped: (This is an error.:String) [], R
untimeException
+ FullyQualifiedErrorId : This is an error.

擲回其他物件

表達式也可以是擲回代表PowerShell進程的物件,如下列範例所示:

C:\PS> throw (get-process PowerShell)

System.Diagnostics.Process (PowerShell)
At line:1 char:6
+ throw <<<<  (get-process PowerShell)
+ CategoryInfo          : OperationStopped: (System.Diagnostics.Process (Pow
erShell):Process) [],
RuntimeException
+ FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)

您可以在$error自動變數中使用 ErrorRecord 物件的 TargetObject 屬性來檢查錯誤。

C:\PS> $error[0].targetobject

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
319      26    61016      70864   568     3.28   5548 PowerShell

您也可以擲回 ErrorRecord 物件或 Microsoft .NET Framework 例外狀況。 下列範例會使用 Throw 關鍵詞擲回 System.FormatException 物件。

C:\PS> $formatError = new-object system.formatexception

C:\PS> throw $formatError

One of the identified items was in an invalid format.
At line:1 char:6
+ throw <<<<  $formatError
+ CategoryInfo          : OperationStopped: (:) [], FormatException
+ FullyQualifiedErrorId : One of the identified items was in an invalid
format.

產生的錯誤

Throw 關鍵詞可以產生 ErrorRecord 物件。 ErrorRecord 物件的 Exception 屬性包含 RuntimeException 物件。 ErrorRecord 對象的其餘部分和 RuntimeException 物件會隨著 Throw 關鍵詞擲回的物件而有所不同。

RunTimeException 物件會包裝在 ErrorRecord 物件中,而 ErrorRecord 物件會自動儲存在$Error自動變數中。

使用 THROW 建立強制參數

您可以使用 Throw 關鍵詞來強制函式參數。

這是使用 Parameter 關鍵詞的強制參數的替代方法。 當您使用強制參數時,系統會提示使用者輸入必要的參數值。 當您使用 Throw 關鍵詞時,命令會停止並顯示錯誤記錄。

例如,參數子表達式中的 Throw 關鍵詞會使 Path 參數成為函式中的必要參數。

在此情況下,Throw 關鍵詞會擲回訊息字串,但如果未指定Path參數,則會有Throw關鍵詞產生終止錯誤。 擲回後面的表達式是選擇性的。

function Get-XMLFiles
{
  param ($path = $(throw "The Path parameter is required."))
  dir -path $path\*.xml -recurse |
    sort lastwritetime |
      ft lastwritetime, attributes, name  -auto
}

另請參閱

about_Break

about_Continue

about_Scopes

about_Trap

about_Try_Catch_Finally