沃尔特个人
主题
about_Trap
简短说明
介绍用于处理终止错误的关键字。
详细说明
终止错误会停止语句运行。如果 Windows PowerShell 不以某些方式处理终止错误,Windows PowerShell
还会停止运行当前管道中的函数或脚本。在其他语言(如 C#)中,将终止错误称为异常。
Trap 关键字指定在出现终止错误时要运行的语句列表。Trap 语句用于处理终止错误并允许继续而不是
停止执行脚本或函数。
语法
Trap 语句的语法如下:
trap [[<error type>]] {<statement list>}
Trap 语句中包含在出现终止错误时要运行的语句列表。Trap 关键字可以选择指定错误类型。
错误类型需要用方括号括起。
一个脚本或命令可具有多个 Trap 语句。Trap 语句可出现在脚本或命令中的任何位置。
捕获所有终止错误
当脚本或命令中出现未另作处理的终止错误时,Windows PowerShell 会检查是否存在可处理该错误的 Trap
语句。如果存在 Trap 语句,Windows PowerShell 会继续运行 Trap 语句中的脚本或命令。
以下示例是一个非常简单的 Trap 语句:
trap {"Error found."}
此 Trap 语句可捕获任何终止错误。以下示例是包含此 Trap 语句的一个函数:
function TrapTest {
trap {"Error found."}
nonsenseString
}
此函数包含一个会导致错误的无用字符串。运行此函数会返回以下结果:
C:\PS> TrapTest
Error found.
以下示例包含一个 Trap 语句,该语句使用 $_ 自动变量显示错误:
function TrapTest {
trap {"Error found: $_"}
nonsenseString
}
运行此版本的函数会返回以下结果:
C:\PS> TrapTest
Error found: The term 'nonsenseString' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included verify that the path
is correct, and then try again.
Trap 语句还可以更复杂。Trap 语句可包含多个条件或函数调用。它可以记录、测试甚至运行其他程序。
捕获指定的终止错误
下例所示 Trap 语句可捕获 CommandNotFoundException 错误类型:
trap [System.Management.Automation.CommandNotFoundException]
{"Command error trapped"}
当函数或脚本遇到与已知命令不匹配的字符串时,此 Trap 语句会显示"Command error trapped"字符
串。在运行 Trap 语句列表中的所有语句之后,Windows PowerShell 会将错误对象写入错误流然后继续运行
脚本。
Windows PowerShe
about_For.help (2) 暂无评价 2页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about_locations.help 暂无评价 2页 免费...
about_aliases.help 暂无评价 3页 免费 about_trap.help 4页 2财富值 about... ?主题 about_Format.ps1xml 简短说明 Windows PowerShell 中的 Format.ps1xml ...
about_For.help (2) 暂无评价 2页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about_aliases.help 暂无评价 3页 免费 ...
about_For.help (2) 暂无评价 2页 2财富值 about_trap.help 4页 2财富值 about_locations.help 暂无评价 2页 免费 about_aliases.help 暂无评价 3页 免费...
about_For.help (2) 暂无评价 2页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about_locations.help 暂无评价 2页 免费...
about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about... ?主题 about_For 简短说明 说明可用于基于条件测试来运行语句的一种语言命令。...
about_For.help (2) 暂无评价 2页 2财富值 Nokia_AT command help 8页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 ...
about_For.help 2页 2财富值 about_For.help (2) 暂无评价 2页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about_...
about_format.ps1xml.help... 6页 2财富值 about_if.help 2页 免费 about_For.help 2页 2财富值 about_trap.help 4页 2财富值 about_arrays.help 暂无...
about_For.help 2页 2财富值 HypExp 2, Expanding Hype... 38页 免费 about_trap.help 4页 2财富值 about_arrays.help 暂无评价 3页 免费 about_...
热门文档