共用方式為


about_Throw

簡短描述

描述 throw 關鍵字,該關鍵字預設會產生導致腳本終止的錯誤。

完整描述

throw該關鍵字預設會造成腳本終止錯誤。 您可以使用 throw 關鍵詞來停止處理命令、函式或腳本。

與語句終止錯誤不同,關鍵字 throw 會解開整個呼叫堆疊。 除非錯誤被區塊或trap語句捕捉try/catch,否則執行會完全停止。

備註

$ErrorActionPreference 可以抑制 throw。 當 設為 SilentlyContinueIgnore時,錯誤不會傳播,執行會從下一句繼續。 當呼叫一個進階函式時,參數 -ErrorAction SilentlyContinue會轉換成作用域局部 $ErrorActionPreference 值,因此在該函式內部也會抑制 throw 。 即使被抑制,仍 throw 會記錄在 $Error。 該 Ignore 值僅阻止 $Error 記錄非終止錯誤,如由 $PSCmdlet.ThrowTerminatingError()產生的錯誤。

欲了解更多錯誤類別與 $ErrorActionPreference 行為資訊,請參見 about_Error_Handling

例如,你可以在語句的throw語句區塊中使用關鍵字來回應條件,或在if語句的catch區塊中使用try/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

另請參閱