Powershell 捕获异常类型

问题描述 投票:0回答:2

是否有一种方便的方法来捕获异常类型和内部异常以用于 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

powershell exception
2个回答
10
投票

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

$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,理论上,InnerException可以无限嵌套:

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

但是您可以将

RuntimeException
作为特殊情况处理。甚至 PowerShell 也这样做。看第一个代码示例。即使指定了 inner 异常的类型,也会到达 catch 块。

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

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

注意,如果您想捕获两个异常,则每个命令都需要一个 try-catch。否则,如果第一个失败,第二个将不会执行。此外,您还必须指定

$ErrorActionPreference
"Stop"
才能捕获非终止异常。


0
投票

只是想补充一点,您可以创建异常类型的排序列表,如下所示:

function Get-Exceptions {
  [OutputType([String[]])]
  [String[]]$Exceptions = [AppDomain]::CurrentDomain.GetAssemblies() | foreach {
    try {
      $_.GetExportedTypes().BaseType | where { $_.Fullname -match 'Exception' }
    } catch {}
  }
  return $Exceptions | Sort-Object -Unique
}
© www.soinside.com 2019 - 2024. All rights reserved.