共用方式為


關於_Throw

簡短描述

描述產生終止錯誤的 throw 關鍵詞。

完整描述

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

例如,您可以在 throw 語句的腳本區塊中使用 if 關鍵詞來回應條件,或在 catchtry-catch- 語句的 finally 區塊中。

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

語法

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

throw [<expression>]

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

throw
Exception: ScriptHalted

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

擲回字串

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

throw "This is an error."
Exception: This is an error.

擲回其他物件

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

throw (Get-Process pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)

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

$Error[0].TargetObject
 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
    125   174.44     229.57      23.61    1548   2 pwsh
     63    44.07      81.95       1.75    1732   2 pwsh
     63    43.32      77.65       1.48    9092   2 pwsh

您也可以 throwErrorRecord 物件或 .NET 例外狀況。 下列範例會使用 throw 關鍵詞來擲回 System.FormatException 物件。

$formatError = New-Object System.FormatException
throw $formatError
OperationStopped: One of the identified items was in an invalid format.

產生的錯誤

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

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

使用 throw 建立強制參數

與過去的PowerShell版本不同,請勿使用 throw 關鍵詞進行參數驗證。 如需正確方式,請參閱 about_Functions_Advanced_Parameters

另請參閱