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,为什么会发生这种情况?换句话说,我希望异常不会被捕获,而是在屏幕上看到相应的异常错误消息。
该行为至少出现在 PowerShell Core 7.2.0-rc.1(撰写本文时为当前版本),可以说是一个 bug.
如您所述,System.Management.Automation.RuntimeException
exception type is not a base class of System.IO.FileNotFoundException
,因此不应触发 catch
块。
问题已在 GitHub issue #16392
中报告
也就是说,捕获 System.Management.Automation.RuntimeException
实际上毫无意义,因为它是(从概念上讲)抽象 基础 class 特定的 PowerShell异常类型,例如System.Management.Automation.CommandNotFoundException
.[1]
在实践中,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=]
我最近在学习 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,为什么会发生这种情况?换句话说,我希望异常不会被捕获,而是在屏幕上看到相应的异常错误消息。
该行为至少出现在 PowerShell Core 7.2.0-rc.1(撰写本文时为当前版本),可以说是一个 bug.
如您所述,
System.Management.Automation.RuntimeException
exception type is not a base class ofSystem.IO.FileNotFoundException
,因此不应触发catch
块。问题已在 GitHub issue #16392
中报告
也就是说,捕获
System.Management.Automation.RuntimeException
实际上毫无意义,因为它是(从概念上讲)抽象 基础 class 特定的 PowerShell异常类型,例如System.Management.Automation.CommandNotFoundException
.[1]
在实践中,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=]