當執行這樣一個腳本時:
nonexistingcommand
echo "Hello"
我得到:
nonexistingcommand : 術語'nonexistingcommand'不能作為cmdlet、函式、腳本檔案或可操作程式的名稱被識別。檢查的拼寫
名稱,或 如果包含一個路徑,驗證路徑是否正確和 再次嘗試。
在D:PlaygroundpowershellTest.ps1:2 char: 1
nonexistingcommand
~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (nonexistingcommand:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
尊敬的先生
所以看起來CommandNotFoundException是一個非終結性錯誤。那么為什么如果我
try {
不存在的命令
}
catch [System.Management.Automation.CommandNotFoundException] {
throw {
}
echo "Hello"
在這種情況下,它將退出而不列印 "Hello"。
為什么會這樣呢?
CodePudding
不幸的是,PowerShell有兩種型別的終止錯誤:
陳述句終止錯誤,默認情況下,它只終止包圍的陳述句。
默認情況下,執行恢復,即通過下一個陳述句(
echo "Hello"在你的例子中)CommandNotFoundException是這種錯誤的一個實體。相比之下,non終止性錯誤繼續處理,即使是包圍的陳述句,如果有進一步的管道輸入的話。
Script終止(執行緒終止)錯誤,它終止了包圍的腳本和整個呼叫堆疊。
throw陳述句觸發,從PowerShell代碼中呼叫,而不是由二進制(編譯的)cmdlets觸發。try { ... } catch { ... } finally { ... } 陳述句沒有區分這兩種子型別:它捕獲它們都。
- 鑒于你的
catch塊包含一個無引數的throw陳述句,它隱含地轉發了觸發錯誤的錯誤,你有效地將statement終止的錯誤變成了script終止的錯誤,所以執行在這里結束。
類似地,設定$ErrorActionPreference偏好變數為'Stop'導致所有型別的錯誤(由PowerShell命令[1]發出),包括非終止錯誤,整體終止了執行。換句話說。非終止和陳述句終止的錯誤都被提升為腳本終止的錯誤。
有關 PowerShell 令人驚訝的復雜錯誤處理的全面概述,請參閱GitHub docs issue #1583。
[1] 至少在控制臺(終端)的本地、前臺呼叫外部程式時,stderr輸出默認不通過PowerShell的錯誤流進行路由,因此不受 uj5u.com熱心網友回復: 上述說明命令未被發現的錯誤是一個終止性錯誤。當遇到這樣的錯誤時,Powershell管道會停止執行。只有catch塊內的陳述句被執行。
要知道終止性和非終止性錯誤的區別,請查看這個鏈接。https://www.tutorialspoint.com/what-is-terminating-and-non-terminating-errors-in-powershell 如果某些陳述句在遇到終止性錯誤時也要執行,請在finally中指定這些陳述句: 上面將列印
標籤:$ErrorActionPreference影響。
try {
nonexistingcommand
}
catch [System.Management.Automation.CommandNotFoundException] {
throw {
}
finally {
echo "Hello"
}
Hello
