[英]Powershell: Using the Handle method of an Aggregate Exception in a Try/Catch block
我有一個任務,它執行大約50-60個可能的設備的反向DNS查找。 在任何情況下都不會拋出任何聚合異常。
如果僅通過控制台輸出(沒有紅色文本),我似乎可以運行,但是仍然可以在$ Error變量中找到異常。
到目前為止,我一直找不到在PowerShell中使用Handle方法的示例。
我不打算從以下鏈接獲得示例,但是我對C#或VB不太熟悉。 我可能無法轉換到PowerShell。
我想知道的是...我在哪里出錯了,或者實際處理了異常?
下面的代碼應說明我陷入困境的原因。 它將創建一個由3個異步反向DNS查找組成的任務,該查找應失敗。 調用WaitAll應該會產生預期的聚集異常並似乎已被處理,但仍在$ Error中觀察到。
$Task = @('testComp1','testComp2','testComp3') | ForEach-Object {
[pscustomobject]@{
Computername = $_
Task = [System.Net.DNS]::GetHostAddressesAsync($_)
}
}
try
{
[Void][Threading.Tasks.Task]::WaitAll($Task.Task)
}
catch [System.AggregateException]
{
$_.Exception.Handle({
param($ex)
if ( $ex.GetType().Name -eq 'SocketException' ) {
Write-Host 'Expected SocketException'
return $true
} else {
return $false
}
})
}
$Error[0]
與$Error
沒有關系。
Handle
方法就像對AggregateException
的異常的過濾器一樣。
謂詞返回false的異常最終將引發新的AggregateException
。
請參閱MSDN上的備注。
謂詞的每次調用都返回true或false,以指示是否處理了Exception。 在所有調用之后,如果未處理任何異常,則所有未處理的異常將放入一個新的AggregateException中,該異常將被拋出。
一個例子。
在此之下,將拋出包含DivideByZeroException
和IndexOutOfRangeException
的AggregateException
。
注意,第一個catch
塊顯示2個內部異常(#0和#1)。
僅處理IndexOutOfRangeException
。
這將導致引發新的AggregateException
,但是這次僅包含DivideByZeroException
。 請注意,第二個catch
塊僅顯示1個內部異常。
try
{
try
{
$divideByZeroException = (New-Object -TypeName System.DivideByZeroException)
$indexOutOfRangeException = (New-Object -TypeName System.IndexOutOfRangeException)
throw (New-Object -TypeName System.AggregateException -ArgumentList $divideByZeroException,$indexOutOfRangeException)
}
catch [System.AggregateException]
{
$_.Exception.ToString() | out-host
# System.AggregateException: One or more errors occurred. ---> System.DivideByZeroException: Attempted to divide by zero.
# --- End of inner exception stack trace ---
# ---> (Inner Exception #0) System.DivideByZeroException: Attempted to divide by zero.<---
# ---> (Inner Exception #1) System.IndexOutOfRangeException: Index was outside the bounds of the array.<---
$_.Exception.Handle({
param($ex)
if ($ex.GetType().Name -eq 'IndexOutOfRangeException' ) {
return $true
} else {
return $false
}
})
}
}
catch [System.AggregateException]
{
$_.Exception.ToString() | out-host
# System.AggregateException: One or more errors occurred. ---> System.DivideByZeroException: Attempted to divide by zero.
# --- End of inner exception stack trace ---
# at System.AggregateException.Handle(Func`2 predicate)
# at CallSite.Target(Closure , CallSite , Object , ScriptBlock )
#---> (Inner Exception #0) System.DivideByZeroException: Attempted to divide by zero.<---
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.