关于抛出

简短说明

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

详细说明

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

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

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

SYNTAX

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

throw [<expression>]

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

C:\PS> throw

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

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

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

使用 THROW 创建必需参数

可以使用 Throw 关键字 (keyword) 使函数参数成为必需参数。

这是使用参数关键字 (keyword) 的必需参数的替代方法。 使用必需参数时,系统会提示用户输入所需的参数值。 使用引发关键字 (keyword) 时,命令会停止并显示错误记录。

例如,参数子表达式中的 Throw 关键字 (keyword) 使 Path 参数成为函数中的必需参数。

在这种情况下,Throw 关键字 (keyword) 会引发消息字符串,但如果未指定 Path 参数,则引发关键字 (keyword) 会生成终止错误。 Throw 后面的表达式是可选的。

function Get-XMLFiles
{
  param ($path = $(throw "The Path parameter is required."))
  dir -path $path\*.xml -recurse |
    sort lastwritetime |
      ft lastwritetime, attributes, name  -auto
}

另请参阅

about_Break

about_Continue

about_Scopes

about_Trap

about_Try_Catch_Finally