AggregateException 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
代表應用程式執行過程中發生的一個或多個錯誤。
public ref class AggregateException : Exception
public class AggregateException : Exception
[System.Serializable]
public class AggregateException : Exception
type AggregateException = class
inherit Exception
[<System.Serializable>]
type AggregateException = class
inherit Exception
Public Class AggregateException
Inherits Exception
- 繼承
- 屬性
範例
以下範例會捕捉該 AggregateException 例外,並呼叫 Handle 該方法來處理其中包含的每個例外。 編譯並執行帶有第一個 task1 變數的範例時,應該會產生 AggregateException 包含 UnauthorizedAccessException 例外的物件。 註解該行、取消註解 task1 第二個變數,然後編譯執行範例,會產生 AggregateException 包含 IndexOutOfRangeException 例外的物件。
using System;
using System.IO;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
// Get a folder path whose directories should throw an UnauthorizedAccessException.
string path = Directory.GetParent(
Environment.GetFolderPath(
Environment.SpecialFolder.UserProfile)).FullName;
// Use this line to throw UnauthorizedAccessException, which we handle.
Task<string[]> task1 = Task<string[]>.Factory.StartNew(() => GetAllFiles(path));
// Use this line to throw an exception that is not handled.
// Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } );
try
{
await task1;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Caught unauthorized access exception-await behavior");
}
catch (AggregateException ae)
{
Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
ae.Handle((x) =>
{
if (x is UnauthorizedAccessException) // This we know how to handle.
{
Console.WriteLine("You do not have permission to access all folders in this path.");
Console.WriteLine("See your network administrator or try another path.");
return true;
}
return false; // Let anything else stop the application.
});
}
Console.WriteLine("task1 Status: {0}{1}", task1.IsCompleted ? "Completed," : "",
task1.Status);
}
static string[] GetAllFiles(string str)
{
// Should throw an UnauthorizedAccessException exception.
return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories);
}
}
// The example displays the following output if the file access task is run:
// You do not have permission to access all folders in this path.
// See your network administrator or try another path.
// task1 Status: Completed,Faulted
// It displays the following output if the second task is run:
// Unhandled Exception: System.AggregateException: One or more errors occurred. ---
// > System.IndexOutOfRangeException: Index was outside the bounds of the array.
// at Example.<Main>b__0()
// at System.Threading.Tasks.Task.Execute()
// --- End of inner exception stack trace ---
// at System.AggregateException.Handle(Func`2 predicate)
// at Example.Main(String[] args)
open System
open System.IO
open System.Threading.Tasks
let getAllFiles str =
// Should throw an UnauthorizedAccessException exception.
System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories)
// Get a folder path whose directories should throw an UnauthorizedAccessException.
let path =
let directory =
Environment.SpecialFolder.UserProfile
|> Environment.GetFolderPath
|> Directory.GetParent
directory.FullName
// Use this line to throw an exception that is not handled.
// let task1 = Task<string []>.Factory.StartNew(fun () -> raise (IndexOutOfRangeException()) )
let task1 = Task.Factory.StartNew(fun () -> getAllFiles (path))
let execute () =
try
task1.Wait()
with
| :? UnauthorizedAccessException -> printfn "Caught unauthorized access exception-await behavior"
| :? AggregateException as ae ->
printfn "Caught aggregate exception-Task.Wait behavior"
ae.Handle (fun x ->
match x with
| :? UnauthorizedAccessException ->
printfn "You do not have permission to access all folders in this path."
printfn "See your network administrator or try another path."
true
| _ -> false)
printfn $"""task1 Status: {if task1.IsCompleted then "Completed," else ""}{task1.Status}"""
execute ()
// The example displays the following output if the file access task is run:
// You do not have permission to access all folders in this path.
// See your network administrator or try another path.
// task1 Status: Completed,Faulted
// It displays the following output if the second task is run:
// Unhandled exception. System.AggregateException: One or more errors occurred. (Index was outside the bounds of the array.) (Index was outside the bounds of the array.)
// ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
// at Exception1.task1@19.Invoke()
// at System.Threading.Tasks.Task`1.InnerInvoke()
// at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
// at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
// --- End of stack trace from previous location ---
// at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
// at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
// --- End of inner exception stack trace ---
// at System.AggregateException.Handle(Func`2 predicate)
// at <StartupCode$exception1>.$Exception1.main@()
Imports System.IO
Imports System.Threading.Tasks
Module Example
Sub Main()
' Get a folder path whose directories should throw an UnauthorizedAccessException.
Dim path As String = Directory.GetParent(
Environment.GetFolderPath(
Environment.SpecialFolder.UserProfile)).FullName
' Use this line to throw UnauthorizedAccessException, which we handle.
Dim task1 = Task(Of String()).Factory.StartNew(Function() GetAllFiles(path))
' Use this line to throw an exception that is not handled.
' Task task1 = Task.Factory.StartNew(Sub() Throw New IndexOutOfRangeException() )
Try
task1.Wait()
Catch ae As AggregateException
ae.Handle(Function(x)
If TypeOf (x) Is UnauthorizedAccessException Then ' This we know how to handle
Console.WriteLine("You do not have permission to access all folders in this path.")
Console.WriteLine("See your network administrator or try another path.")
Return True
Else
Return False ' Let anything else stop the application.
End If
End Function)
End Try
Console.WriteLine("task1 Status: {0}{1}", If(task1.IsCompleted, "Completed,", ""),
task1.Status)
End Sub
Function GetAllFiles(ByVal str As String) As String()
' Should throw an UnauthorizedAccessException exception.
Return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories)
End Function
End Module
備註
AggregateException 用於將多個失敗整合到單一可拋出的例外物件中。 它被廣泛用於任務平行函式庫(TPL)和平行 LINQ(PLINQ)。 如需詳細資訊,請參閱 例外狀況處理 和 如何:處理PLINQ查詢中的例外狀況。 欲了解更多資訊,請參閱 .NET Matters 部落格中的 Aggregating Exceptions條目。
建構函式
| 名稱 | Description |
|---|---|
| AggregateException() |
初始化該類別的新實例 AggregateException ,並以系統提供的訊息描述錯誤。 |
| AggregateException(Exception[]) |
初始化該類別的新實例 AggregateException ,並引用導致該例外的內部例外。 |
| AggregateException(IEnumerable<Exception>) |
初始化該類別的新實例 AggregateException ,並引用導致該例外的內部例外。 |
| AggregateException(SerializationInfo, StreamingContext) |
已淘汰.
使用串行化數據,初始化 AggregateException 類別的新實例。 |
| AggregateException(String, Exception) |
初始化類別的新實例 AggregateException ,並附上指定的錯誤訊息及導致該異常的內部例外的參考。 |
| AggregateException(String, Exception[]) |
初始化類別的新實例 AggregateException ,並以指定的錯誤訊息及導致該異常的內部例外來參考。 |
| AggregateException(String, IEnumerable<Exception>) |
初始化類別的新實例 AggregateException ,並以指定的錯誤訊息及導致該異常的內部例外來參考。 |
| AggregateException(String) |
初始化類別的新實例 AggregateException ,並以指定訊息描述錯誤。 |
屬性
| 名稱 | Description |
|---|---|
| Data |
取得索引鍵/值組的集合,提供例外狀況的其他使用者定義資訊。 (繼承來源 Exception) |
| HelpLink |
取得或設定與這個例外狀況相關聯的說明檔連結。 (繼承來源 Exception) |
| HResult |
取得或設定 HRESULT,這是指派給特定例外狀況的編碼數值。 (繼承來源 Exception) |
| InnerException |
會取得 Exception 造成目前例外的實例。 (繼承來源 Exception) |
| InnerExceptions |
會取得一個只讀的集合,包含 Exception 導致當前例外的實例。 |
| Message |
會收到描述例外的訊息。 |
| Message |
取得描述目前例外狀況的訊息。 (繼承來源 Exception) |
| Source |
取得或設定造成錯誤之應用程式或物件的名稱。 (繼承來源 Exception) |
| StackTrace |
取得呼叫堆疊上即時框架的字串表示。 (繼承來源 Exception) |
| TargetSite |
取得擲回目前例外狀況的方法。 (繼承來源 Exception) |
方法
| 名稱 | Description |
|---|---|
| Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
| Flatten() |
將一個 AggregateException 實例扁平化成一個新的實例。 |
| GetBaseException() |
回傳 Exception that,是此例外的根本原因。 此例外要麼是根例外,要麼是第一個 AggregateException 包含多個內部例外或完全沒有內部例外的例外。 |
| GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
已淘汰.
使用串行化數據,初始化 AggregateException 類別的新實例。 |
| GetType() |
取得目前實例的運行時間類型。 (繼承來源 Exception) |
| Handle(Func<Exception,Boolean>) |
在每個 Exception 包含 AggregateException於 的 上呼叫一個處理器。 |
| MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
| ToString() |
建立並回傳當前 AggregateException的字串表示。 |
事件
| 名稱 | Description |
|---|---|
| SerializeObjectState |
已淘汰.
發生於例外狀況串行化以建立例外狀況狀態物件,其中包含例外狀況的串行化數據。 (繼承來源 Exception) |
適用於
執行緒安全性
所有公開且受保護的成員 AggregateException 皆為執行緒安全,且可同時從多個執行緒使用。