這些天我正在學習 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,為什么會發生這種情況?換句話說,我期望不會捕獲例外,而是在螢屏上看到相應的例外錯誤訊息。
uj5u.com熱心網友回復:
該行為至少出現在 PowerShell Core 7.2.0-rc.1(截至撰寫本文時),可以說是一個錯誤。
正如您所說,
System.Management.Automation.RuntimeException例外型別不是的基類System.IO.FileNotFoundException,因此不應觸發該catch塊。該問題已在GitHub 問題 #16392 中報告
也就是說,捕獲
System.Management.Automation.RuntimeException實際上毫無意義,因為它是(從概念上講)特定PowerShell 例外型別的抽象基類,例如. [1]System.Management.Automation.CommandNotFoundException
在實踐中,catch [System.Management.Automation.RuntimeException]似乎表現得像一個unqualified catch,即它捕獲任何例外(沒有被另一個更具體的型別catch塊捕獲,如果存在)。
如果,在較高的水平,則需要從派生的例外型別之間進行區分System.Management.Automation.RuntimeException對那些不是,則可以使用非限定catch塊,可以在其中使用-is的型別(-inheritance)/介面測驗操作員:
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使用where 的例子是由觸發的陳述句終止錯誤1 / 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354132.html
