且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell捕获异常类型

更新时间:2023-11-11 12:31:16

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

First of all, you can explicitly catch specific exception types:

$ErrorActionPreference = "Stop"
try {
    1/0
}
catch [System.DivideByZeroException] {
    $_.Exception.GetType().Name
}
try {
    gi "c:\x"
}
catch [System.Management.Automation.ItemNotFoundException] {
    $_.Exception.GetType().Name
}

DivideByZeroException 基本上只是 RuntimeException 的InnerException,从理论上讲,InnerExceptions可以无休止地嵌套:

The DivideByZeroException is basically just the InnerException of RuntimeException, and theoretically, the InnerExceptions could be endlessly nested:

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

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

BUT you can handle RuntimeException as a special case. Even PowerShell does so. Look at the first code example. The catch-block is reached even though the type of the inner exception is specified.

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

You could do something similar yourself:

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

注意,如果要捕获两个异常,则每个命令需要一个try-catch.否则,如果第一个失败,则第二个将不会执行.另外,您还必须为"Stop" 指定 $ ErrorActionPreference 来捕获非终止异常.

NOTE that you need one try-catch per command, if you want to catch both exceptions. Else the 2nd will not be executed if the 1st one fails. Also you have to specify $ErrorActionPreference to "Stop" to catch also non-terminating exceptions.