简短说明
描述引发关键字,该关键字生成终止错误。
详细说明
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。