Home > other >  PowerShell: strange handling of exception
PowerShell: strange handling of exception

Time:11-09

I am learning PowerShell these days and have come across some odd behavior. After running the following code, whose only purpose is to understand exception handling:

try

{

throw [System.IO.FileNotFoundException]::new("Thrown a file not found exception")

}

catch [System.Management.Automation.RuntimeException]

{

    Write-Output "Entered catch"

}

I get that "Entered catch" is shown onscreen. Why does this happen, if according to online documentation System.IO.FileNotFoundException does not have System.Management.Automation.RuntimeException in its line of inheritance? In other words, I was expecting the exception not to be caught and the corresponding exception error message to be seen onscreen instead.

CodePudding user response:


In practice, catch [System.Management.Automation.RuntimeException] seems to behave like an unqualified catch, i.e. it catches any exception (not caught by another, more specific, typed catch block, if present).

If, at a high level, you need to distinguish between exception types derived from System.Management.Automation.RuntimeException vs. those that aren't, you can use an unqualified catch block in which you can use -is, the type(-inheritance) / interface test operator:

try
{
  throw [System.IO.FileNotFoundException]::new("Thrown a file not found exception")
}
catch {

  $isPSException = $_.Exception -is [System.Management.Automation.RuntimeException]

  "Exception is RuntimeException-derived: $isPSException"
}

[1] A rare example of where System.Management.Automation.RuntimeException is used directly is the statement-terminating error triggered by 1 / 0

  • Related