about_Throw

简短说明

介绍 Throw 关键字,用于生成终止错误。

长说明

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

例如,可以使用 If 语句的脚本块中的 Throw 关键字 (keyword) 来响应条件或 Try-Catch-Finally 语句的 Catch 块。 还可以在参数声明中使用 Throw 关键字 (keyword) ,使函数参数成为必需参数。

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

语法

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

throw [<expression>]

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

C:\PS> throw

Exception: ScriptHalted

如果在不带表达式的 Catch 块中使用了 Throw 关键字 (keyword) ,则会再次引发当前的 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 关键字 (keyword) 引发 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 关键字 (keyword) 可以生成 ErrorRecord 对象。 ErrorRecord 对象的 Exception 属性包含 RuntimeException 对象。 ErrorRecord 对象和 RuntimeException 对象的其余部分因 Throw 关键字 (keyword) 引发的对象而异。

RunTimeException 对象包装在 ErrorRecord 对象中,ErrorRecord 对象会自动保存在$Error自动变量中。

使用 Throw 创建必需参数

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

另请参阅