about_Throw

简短说明

描述throw生成终止错误的关键字 (keyword) 。

长说明

关键字 (keyword) throw 会导致终止错误。 可以使用throw关键字 (keyword) 停止处理命令、函数或脚本。

例如,可以使用语句的脚本块中的关键字 (keyword) 来响应条件或在语句块try-catch-finally中。catchifthrow

关键字 (keyword) throw 可以引发任何对象,例如用户消息字符串或导致错误的 对象。

语法

关键字 (keyword) 的throw语法如下:

throw [<expression>]

语法中的 throw 表达式是可选的。 throw如果 语句未出现在块中catch,并且不包含表达式,则会生成 ScriptHalted 错误。

throw
Exception: ScriptHalted

throw 如果在没有表达式的块中使用catch关键字 (keyword) ,它将再次引发当前的 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)

可以使用自动变量中的 $ErrorErrorRecord 对象的 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 关键字 (keyword) 引发 System.FormatException 对象。

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

生成的错误

关键字 (keyword) throw 可以生成 ErrorRecord 对象。 ErrorRecord 对象的 Exception 属性包含 RuntimeException 对象。 ErrorRecord 对象和 RuntimeException 对象的其余部分因引发的对象而异。

对象 throw 包装在 ErrorRecord 对象中,ErrorRecord 对象将自动保存在自动变量中 $Error

使用 throw 创建必需参数

与以前版本的 PowerShell 不同,请勿将throw关键字 (keyword) 用于参数验证。 有关正确方法 ,请参阅about_Functions_Advanced_Parameters

另请参阅