【问题标题】:Powershell catching exception typePowershell 捕获异常类型
【发布时间】: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


【解决方案1】:

首先,您可以显式捕获特定的异常类型:

$ErrorActionPreference = "Stop"

try {
    1 / 0
}
catch [System.DivideByZeroException] {
    $_.Exception.GetType().Name
}

try {
    Get-Item "c:\does-not-exist"
}
catch [System.Management.Automation.ItemNotFoundException] {
    $_.Exception.GetType().Name
}

DivideByZeroException基本上就是RuntimeException的InnerException,理论上InnerExceptions可以无限嵌套:

catch {
    $exception = $_.Exception
    do {
        $exception.GetType().Name
        $exception = $exception.InnerException
    } while ($exception)
}

但是您可以将RuntimeException 作为特殊情况处理。甚至 PowerShell 也是如此。看第一个代码示例。即使指定了 inner 异常的类型,也会到达 catch-block。

你可以自己做类似的事情:

catch {
    $exception = $_.Exception
    if ($exception -is [System.Management.Automation.RuntimeException] -and $exception.InnerException) {
        $exception = $exception.InnerException
    }
    $exception.GetType().Name
}

注意,如果您想同时捕获两个异常,则每个命令都需要一个 try-catch。否则,如果第一个失败,则不会执行第二个。此外,您还必须指定 $ErrorActionPreference"Stop" 才能捕获非终止异常。

【讨论】:

  • 这很好地回答了它,无限嵌套的 InnerExceptions 解释了为什么无法通过相对简单的命令来确定类型。我可能会将此代码用作查找异常类型,希望您不要介意。
【解决方案2】:

【讨论】:

  • 我试图引起错误并从中提取要放入括号的内容。最好使用一个命令。
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2010-10-08
  • 2015-11-17
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
相关资源
最近更新 更多