简短说明
描述引发关键字,该关键字生成终止错误。
详细说明
Throw 关键字会导致终止错误。 您可以使用 Throw 关键字停止对命令、函数或脚本的处理。
例如,可以在 If 语句的脚本块中使用 Throw 关键字来响应条件,也可以在 Try-Catch-Finally 语句的 Catch 块中使用 Throw 关键字。 您还可以在参数声明中使用 Throw 关键字,使函数参数为必需参数。
Throw 关键字可以引发任何对象,例如用户消息字符串或导致错误的对象。
语法
Throw 关键字的语法如下:
throw [<expression>]
Throw 语法中的表达式是可选的。 当 Throw 语句未出现在 Catch 块中,并且不包含表达式时,它将生成 ScriptHalted 错误。
C:\PS> throw
ScriptHalted
At line:1 char:6
+ throw <<<<
+ CategoryInfo : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted
如果在没有表达式的 Catch 块中使用 Throw 关键字,它将再次引发当前 RuntimeException。 有关更多信息,请参阅 about_Try_Catch_Finally。
抛出字符串
Throw 语句中的可选表达式可以是字符串,如以下示例所示:
C:\PS> 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 进程的对象的对象,如以下示例所示:
C:\PS> throw (get-process PowerShell)
System.Diagnostics.Process (PowerShell)
At line:1 char:6
+ throw <<<< (get-process PowerShell)
+ CategoryInfo : OperationStopped: (System.Diagnostics.Process (Pow
erShell):Process) [],
RuntimeException
+ FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)
您可以使用 $error 自动变量中 ErrorRecord 对象的 TargetObject 属性来检查错误。
C:\PS> $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
还可以引发 ErrorRecord 对象或 Microsoft .NET Framework 异常。 下面的示例使用 Throw 关键字引发 System.FormatException 对象。
C:\PS> $formatError = new-object system.formatexception
C:\PS> 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 关键字引发的对象而变化。
RunTimeException 对象包装在 ErrorRecord 对象中,ErrorRecord 对象自动保存在 $Error 自动变量中。
使用 THROW 创建强制参数
您可以使用 Throw 关键字将函数参数设为必填项。
这是使用 Parameter 关键字的 Mandatory 参数的替代方法。 当您使用 Mandatory (强制) 参数时,系统会提示用户输入所需的参数值。 使用 Throw 关键字时,该命令将停止并显示错误记录。
例如,参数子表达式中的 Throw 关键字使 Path 参数成为函数中的必需参数。
在这种情况下, Throw 关键字会引发消息字符串,但如果未指定 Path 参数,则 Throw 关键字的存在会生成终止错误。 Throw 后面的表达式是可选的。
function Get-XMLFiles
{
param ($path = $(throw "The Path parameter is required."))
dir -path $path\*.xml -recurse |
sort lastwritetime |
ft lastwritetime, attributes, name -auto
}