通过


about_Throw

简短说明

描述 throw 关键字,该关键字默认生成脚本终止错误。

详细说明

默认情况下,关键字 throw 会导致脚本终止错误。 可以使用 throw 关键字停止对命令、函数或脚本的处理。

与语句终止错误不同, throw 关键字将展开整个调用堆栈。 除非阻止或trap语句捕获try/catch错误,否则执行将完全停止。

注释

$ErrorActionPreference 可以抑制 throw。 如果设置为 SilentlyContinue 或设置为, Ignore则错误不会传播和执行在下一个语句中继续。 使用 <a0/a0> 调用高级函数时,该参数将转换为范围本地值,因此它还会禁止在该函数内部。 即使已取消,throw仍会记录一个条目。$Error 该值 Ignore 仅阻止 $Error 记录非终止错误,如由这些 $PSCmdlet.ThrowTerminatingError()错误生成的错误。

有关错误类别和 $ErrorActionPreference 行为的详细信息,请参阅 about_Error_Handling

例如,可以使用throw语句语句块if中的关键字来响应条件或在语句块catchtry/catch/finally

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

Syntax

throw 关键字的语法如下:

throw [<expression>]

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

throw
ScriptHalted
At line:1 char:6
+ throw <<<<
+ CategoryInfo          : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted

如果在没有表达式的 throw 块中使用 catch 关键字,它将再次引发当前 RuntimeException。 有关详细信息,请参阅 about_Try_Catch_Finally

引发字符串

throw 语句中的可选表达式可以是字符串,如以下示例所示:

throw "This is an error."
This is an error.
At line:1 char:6
+ throw <<<<  "This is an error."
+ CategoryInfo          : OperationStopped: (This is an error.:String) [], R
untimeException
+ FullyQualifiedErrorId : This is an error.

引发其他对象

表达式还可以是一个对象,该对象引发表示 PowerShell 进程的对象,如以下示例所示:

throw (Get-Process pwsh)
At line:1 char:6
+ throw <<<<  (Get-Process powershell)
+ CategoryInfo          : OperationStopped: (System.Diagnostics.Process (Pow
erShell):Process) [],
RuntimeException
+ FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)

可以使用 自动变量中 ErrorRecord 对象的 TargetObject 属性来查看错误。$Error

$Error[0].TargetObject
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
319      26    61016      70864   568     3.28   5548 PowerShell

你还可以 throw ErrorRecord 对象或 .NET 异常。 以下示例使用 throw 关键字引发 System.FormatException 对象。

$formatError = New-Object System.FormatException
throw $formatError
One of the identified items was in an invalid format.
At line:1 char:6
+ throw <<<<  $formatError
+ CategoryInfo          : OperationStopped: (:) [], FormatException
+ FullyQualifiedErrorId : 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

另请参阅