簡短描述
描述 Throw 關鍵詞,其會產生終止錯誤。
完整描述
Throw 關鍵字會導致終止錯誤。 您可以使用 Throw 關鍵字停止對命令、函數或腳本的處理。
例如,可以在 If 語句的腳本塊中使用 Throw 關鍵字來響應條件,也可以在 Try-Catch-Finally 語句的 Catch 塊中使用 Throw 關鍵字。 您還可以在參數聲明中使用 Throw 關鍵字,使函數參數為必需參數。
Throw 關鍵字可以引發任何物件,例如使用者消息字串或導致錯誤的物件。
語法
Throw 關鍵字的語法如下:
throw [<expression>]
Throw 語法中的表達式是可選的。 當 Throw 語句未出現在 Catch 塊中,並且不包含表示式時,它將生成 ScriptHalted 錯誤。
C:\PS> throw
Exception: ScriptHalted
如果在沒有表達式的 Catch 塊中使用 Throw 關鍵字,它將再次引發當前 RuntimeException。 有關更多資訊,請參閱 about_Try_Catch_Finally。
擲回字串
Throw 語句中的可選運算式可以是字串,如以下範例所示:
C:\PS> throw "This is an error."
Exception: This is an error.
擲回其他物件
表達式也可以是擲回代表PowerShell進程的物件的物件,如下列範例所示:
C:\PS> throw (get-process Pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)
您可以使用 $error 自動變數中 ErrorRecord 物件的 TargetObject 屬性來檢查錯誤。
C:\PS> $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
還可以引發 ErrorRecord 物件或 .NET 異常。 下面的示例使用 Throw 關鍵字引發 System.FormatException 物件。
C:\PS> $formatError = new-object system.formatexception
C:\PS> throw $formatError
OperationStopped: One of the identified items was in an invalid format.
產生的錯誤
Throw 關鍵字可以生成 ErrorRecord 物件。 ErrorRecord 物件的 Exception 屬性包含一個 RuntimeException 物件。 ErrorRecord 物件和 RuntimeException 對象的其餘部分隨 Throw 關鍵字引發的物件而變化。
RunTimeException 對象包裝在 ErrorRecord 物件中,ErrorRecord 物件自動儲存在 $Error 自動變數中。
使用 Throw 建立強制參數
與以前版本的 PowerShell 不同,請勿使用 Throw 關鍵字進行參數驗證。 如需正確方式,請參閱 about_Functions_Advanced_Parameters。