about_Throw
簡短描述
描述 throw
產生終止錯誤的關鍵詞。
完整描述
關鍵詞 throw
會造成終止錯誤。 您可以使用 throw
關鍵詞來停止命令、函式或腳本的處理。
例如,您可以在語句的if
文稿區塊中使用 關鍵詞來回應條件或 語句區塊。catch
catch
try
--finally
throw
throw
關鍵詞可以擲回任何物件,例如使用者訊息字串或造成錯誤的物件。
Syntax
關鍵詞的 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)
您可以使用 Automatic 變數中 $Error
ErrorRecord 物件的 TargetObject 屬性來檢查錯誤。
$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
您也可以 throw
使用 ErrorRecord 物件或 .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 。