共用方式為


about_Throw

簡短描述

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

詳細描述

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

例如,您可以在語句的文稿區塊中使用 throw 關鍵詞來回應條件或在 語句的finallytry-catch- 區塊中。catchif

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

語法

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

throw [<expression>]

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

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

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

擲回字串

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

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進程的物件的物件,如下列範例所示:

throw (Get-Process pwsh)
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 屬性來檢查錯誤。

$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

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

$formatError = New-Object System.FormatException
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會包裝在 ErrorRecord 物件中,而且 ErrorRecord 物件會自動儲存在自動變數中$Error

使用 throw 來建立強制參數

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

另請參閱