[英]Powershell: Throwing Exception in Catch block terminates but does not output Exception to console
我最近開始遇到這個奇怪的問題,我的異常被捕獲在我的 catch 塊中,但是在重新拋出它時會終止腳本(如預期的那樣),但不會將重新拋出的異常寫入控制台。 我不關心正在拋出的特定異常,我只關心重新拋出異常並且堆棧跟蹤是 output 到控制台。 我正在使用 PowerShell 4。
try {
$variable1 = 'value1'
$variable2 = 'value2'
[string[]]$variable3 = 'value3'
[Collections.Generic.List[Microsoft.PowerShell.Commands.MatchInfo]]$matches = New-Object Collections.Generic.List[Microsoft.PowerShell.Commands.MatchInfo]
$matches = `
Get-Matches `
-Param1 $variable1 `
-Param2 $variable2 `
-Param3 $variable3 `
-Silent $true
Write-Host `n`nTotal Matches Found: $matches.Count
} catch {
throw $_
}
我還嘗試對 catch 塊進行以下更改:
} catch {
throw
}
} catch {
throw $_.Exception
}
} catch {
throw $_.Exception.Message
}
} catch {
throw $error[0].Exception
}
} catch {
throw $error[0].Exception.Message
}
要 output 在 catch 塊中出現屏幕異常,請使用以下命令:
try {
#code
} catch {
#handle exception
Write-Output $_.Exception.Message
}
此外,您的throw
應該在您的 try 語句中。 在catch
塊中拋出異常是沒有意義的,因為已經拋出並捕獲了一個異常!
try {
#code
if($something -ne $right) {
throw "Something isn't right!"
}
} catch {
#handle exception
Write-Output $_.Exception.Message
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.