PowerShell:奇怪的异常处理

PowerShell: strange handling of exception

我最近在学习 PowerShell,遇到了一些奇怪的行为。在运行之后是下面的代码,其唯一目的是理解异常处理:

try

{

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

}

catch [System.Management.Automation.RuntimeException]

{

    Write-Output "Entered catch"

}

我知道屏幕上显示“已输入捕获”。如果根据在线文档 System.IO.FileNotFoundException 在其继承行中没有 System.Management.Automation.RuntimeException,为什么会发生这种情况?换句话说,我希望异常不会被捕获,而是在屏幕上看到相应的异常错误消息。


在实践中,catch [System.Management.Automation.RuntimeException] 似乎表现得像一个 不合格 catch,即它捕获 任何 异常(未被另一个更具体的类型 catch 块捕获,如果存在的话)。

如果在高层次上,您需要区分从 System.Management.Automation.RuntimeException 派生的异常类型与不是派生的异常类型,您可以使用非限定的 catch 块,您可以在其中使用-is, 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] 直接使用System.Management.Automation.RuntimeException的一个罕见例子是由1 / 0[触发的语句终止错误=69=]