Powershell catching exception type

人盡茶涼 提交于 2020-12-06 12:35:22

问题


Is there a convenient way to catch types of exceptions and inner exceptions for try-catch purposes?

Example code:

$a = 5
$b = Read-Host "Enter number" 
$c = $a / $b #error if $b -eq 0
$d = get-content C:\I\Do\Not\Exist

Row #3 will generate a runtime error with an inner exception (EDIT: fixed this command $Error[1].Exception.InnerException.GetType()), row #4 will generate a "standard"(?) type of exception ($Error[0].Exception.GetType()).

Is it possible to get the desired result from both of these with the same line of code?

Ad1: error from row 3

At -path-:3 char:1

+ $c = $a / $b #error if $b -eq 0
+ ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

Ad2: error from row 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

Edit: To make it clear, I want the result to return DivideByZeroException and ItemNotFoundException in some way


回答1:


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
}

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)
}

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
}

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.




回答2:


Are you trying to catch specific error types like this?

https://blogs.technet.microsoft.com/poshchap/2017/02/24/try-to-catch-error-exception-types/



来源:https://stackoverflow.com/questions/54193643/powershell-catching-exception-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!