[英]Powershell non terminating error and try catch block
我正在使用 power shell 控制台運行以下 power shell 腳本:
$ob1 = "nonexistingclass"
$a = new-object $ob1
Write-Output "Created new object"
Write-Output "End"
這會打印錯誤。 然后繼續打印“Created new object”和“End”。 所以我假設這是一個非終止錯誤。
但是,如果我將 try catch 塊放在新對象周圍,如下所示:
$ob1 = "nonexistingclass"
try
{
$a = new-object $ob1
Write-Output "Created new object"
}
catch
{
Write-Error "Exception Message: $($_.Exception.Message)"
}
Write-Output "End"
在這種情況下,catch 塊被命中並寫入異常消息。
我的問題是:
根據文檔,有兩種類型的 PowerShell 錯誤,終止和非終止。
還有另一種模糊的第三類錯誤。 此類錯誤由try
和trap
,即它們的行為類似於終止,但它們不會在沒有try
或trap
情況下停止執行,即它們的行為類似於非終止。
例如,如果命令名稱未被識別為 cmdlet、函數、腳本文件或可運行程序的名稱,則 PowerShell 會發出錯誤。 此錯誤是否終止? 這取決於。 令人驚訝的是,默認情況下並非如此。
看起來在腳本中不斷使用錯誤操作首選項Stop或try
或trap
塊是一個好主意。 否則半終止錯誤可能會導致問題,因為調用仍在繼續。 請注意,默認的錯誤操作首選項是Continue 。
半終止錯誤的例子:
名單可能會繼續……
假設
測試給出了任何運行時異常都是半終止錯誤的想法。
使用測試腳本查看完整案例 - PowerShellTraps/Errors-of-unusual-type
更新(如評論中所述):
關於此類錯誤詳細信息的官方文檔並不多。 但這里是 PowerShell 文檔庫中的全面討論:
https://github.com/MicrosoftDocs/PowerShell-Docs/issues/1583
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.