共用方式為


AggregateException 類別

定義

代表應用程式執行期間所發生的一或多個錯誤。

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
屬性

範例

下列範例會 AggregateException 攔截例外狀況,並呼叫 Handle 方法來處理它所包含的每個例外狀況。 使用第一 task1AggregateException 變數編譯和執行範例時,應該會產生包含例外狀況 UnauthorizedAccessException 的物件。 將該行批注化、取消批注第二 task1AggregateException 變數,以及編譯和執行範例會產生包含例外狀況 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 ae)
      {
          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 部落格中的 匯總例外 狀況專案。

建構函式

AggregateException()

使用系統提供的錯誤描述訊息,初始化 AggregateException 類別的新執行個體。

AggregateException(Exception[])

使用造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。

AggregateException(IEnumerable<Exception>)

使用造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。

AggregateException(SerializationInfo, StreamingContext)
已淘汰.

使用序列化資料,初始化 AggregateException 類別的新執行個體。

AggregateException(String)

初始化具有指定的錯誤描述訊息之 AggregateException 類別的新執行個體。

AggregateException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 AggregateException 類別的新執行個體。

AggregateException(String, Exception[])

使用指定的錯誤訊息和造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。

AggregateException(String, IEnumerable<Exception>)

使用指定的錯誤訊息和造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。

屬性

Data

取得鍵值組的集合,這些鍵值組會提供關於例外狀況的其他使用者定義資訊。

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。

(繼承來源 Exception)
InnerExceptions

取得造成目前例外狀況之 Exception 執行個體的唯讀集合。

Message

取得描述例外狀況的訊息。

Message

取得描述目前例外狀況的訊息。

(繼承來源 Exception)
Source

取得或設定造成錯誤的應用程式或物件的名稱。

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Flatten()

AggregateException 執行個體簡維成單一新執行個體。

GetBaseException()

傳回這個例外狀況之根本原因的 AggregateException

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

使用序列化資料,初始化 AggregateException 類別的新執行個體。

GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfo

(繼承來源 Exception)
GetType()

取得目前執行個體的執行階段類型。

(繼承來源 Exception)
Handle(Func<Exception,Boolean>)

叫用每個 Exception 上的處理常式,其由這個 AggregateException 所包含。

MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

建立並傳回目前 AggregateException 的字串表示。

事件

SerializeObjectState
已淘汰.

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。

(繼承來源 Exception)

適用於

執行緒安全性

的所有公用和受保護成員 AggregateException 都是安全線程,而且可以從多個線程同時使用。