【发布时间】:2019-01-15 06:20:50
【问题描述】:
有没有一种方便的方法来捕获异常类型和内部异常以用于 try-catch 目的?
示例代码:
$a = 5
$b = Read-Host "Enter number"
$c = $a / $b #error if $b -eq 0
$d = get-content C:\I\Do\Not\Exist
第 3 行将生成带有内部异常的运行时错误(编辑:修复了此命令 $Error[1].Exception.InnerException.GetType()),第 4 行将生成“标准”(?)类型异常($Error[0].Exception.GetType())。
是否有可能使用同一行代码从这两者中获得所需的结果?
Ad1:第 3 行出错
At -path-:3 char:1
+ $c = $a / $b #error if $b -eq 0
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
Ad2:第 4 行出错
get-content : Cannot find path 'C:\I\Do\Not\Exist' because it does not exist.
At -path-:4 char:6
+ $d = get-content C:\I\Do\Not\Exist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\I\Do\Not\Exist:String)
[Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
编辑:为了清楚起见,我希望结果以某种方式返回 DivideByZeroException 和 ItemNotFoundException
【问题讨论】:
-
您尝试过使用
$ErrorActionPreference = "Continue"吗?这只会让代码运行错误。 -
我认为你错了
$Error[1].InnerException- 没有这样的属性。你可以像处理另一个一样做$Error[1].Exception。不知道你想要什么。 -
@marsze 我的错,是 $Error[1].Exception.InnerException.GetType()
标签: powershell exception exception-handling