有没有方便的方法来捕获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
第三行会生成一个带有内部异常的运行时错误(编辑:修正此命令 $Error[1].Exception.InnerException.GetType()),第四行将生成一个“标准”(?)类型的异常($Error[0].Exception.GetType())。
是否可能使用同一行代码从这两个中获得所需的结果?
Ad1:来自第三行的错误
At -path-:3 char:1
+ $c = $a / $b #error if $b -eq 0
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
广告2:第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"
吗?这样可以让代码在错误情况下继续运行。 - Shadowzee$Error[1].InnerException
- 没有这样的属性。你可以像处理其他错误一样使用$Error[1].Exception
。我不确定你想要什么。 - marsze