当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 关于投掷

作者:精品下载站 日期:2024-12-14 02:17:51 浏览:13 分类:玩电脑

关于投掷


简短描述

描述生成终止错误的 throw 关键字。

详细描述

throw 关键字会导致终止错误。您可以使用 throw 关键字来停止命令、函数或脚本的处理。

例如,您可以在 if 语句的脚本块中使用 throw 关键字来响应条件,或者在 catch 语句的 catch 块中使用关键字。 try-catch-finally语句。

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

句法

throw 关键字的语法如下:

throw [<expression>]

throw 语法中的表达式是可选的。当 throw 语句未出现在 catch 块中且不包含表达式时,会生成 ScriptHalted 错误。

throw
Exception: ScriptHalted

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

扔一根绳子

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

throw "This is an error."
Exception: This is an error.

投掷其他物体

该表达式还可以是抛出表示 PowerShell 进程的对象的对象,如以下示例所示:

throw (Get-Process pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)

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

$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 对象。

$formatError = New-Object System.FormatException
throw $formatError
OperationStopped: 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 了解正确方法。

参见

  • about_Break
  • 关于_继续
  • about_范围
  • about_Trap
  • about_Try_Catch_Finally

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯