AggregateException 類別

定義

代表應用程式執行期間所發生的一或多個錯誤。Represents one or more errors that occur during application execution.

public ref class AggregateException : Exception
[System.Serializable]
public class AggregateException : Exception
type AggregateException = class
    inherit Exception
Public Class AggregateException
Inherits Exception
繼承
AggregateException
屬性

範例

下列範例AggregateException會攔截例外狀況, 並Handle呼叫方法來處理它所包含的每個例外狀況。The following example catches the AggregateException exception and calls the Handle method to handle each exception it contains. 使用第一個task1變數編譯和執行此範例, 應該會導致AggregateException包含UnauthorizedAccessException例外狀況的物件。Compiling and running the example with the first task1 variable should result in an AggregateException object that contains an UnauthorizedAccessException exception. 將該行批註化, 取消批註第二task1個變數, 編譯和執行範例會AggregateException產生包含IndexOutOfRangeException例外狀況的物件。Commenting out that line, uncommenting the second task1 variable, and compiling and running the example produces an AggregateException object that contains an IndexOutOfRangeException exception.

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)
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是用來將多個失敗合併成單一的 java.lang.throwable 例外狀況物件。AggregateException is used to consolidate multiple failures into a single, throwable exception object. 它在工作平行程式庫 (TPL)平行 LINQ (PLINQ)中廣泛使用。It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). 如需詳細資訊,請參閱例外狀況處理如何:處理 PLINQ 查詢中的例外狀況For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query. 如需其他資訊, 請參閱 .NET 重要的 blog 中的匯總例外狀況專案。For additional information, see the Aggregating Exceptions entry in the .NET Matters blog.

建構函式

AggregateException()

以系統提供的錯誤說明訊息,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with a system-supplied message that describes the error.

AggregateException(Exception[])

使用造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with references to the inner exceptions that are the cause of this exception.

AggregateException(IEnumerable<Exception>)

使用造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with references to the inner exceptions that are the cause of this exception.

AggregateException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with serialized data.

AggregateException(String)

使用指定的錯誤說明訊息,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with a specified message that describes the error.

AggregateException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with a specified error message and a reference to the inner exception that is the cause of this exception.

AggregateException(String, Exception[])

使用指定的錯誤訊息和造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception.

AggregateException(String, IEnumerable<Exception>)

使用指定的錯誤訊息和造成這個例外狀況原因的內部例外狀況參考,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception.

屬性

Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(繼承來源 Exception)
InnerExceptions

取得造成目前例外狀況之 Exception 執行個體的唯讀集合。Gets a read-only collection of the Exception instances that caused the current exception.

Message

取得描述例外狀況的訊息。Gets a message that describes the exception.

Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Flatten()

AggregateException 執行個體簡維成單一新執行個體。Flattens an AggregateException instances into a single, new instance.

GetBaseException()

傳回這個例外狀況之根本原因的 AggregateExceptionReturns the AggregateException that is the root cause of this exception.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

使用序列化資料,初始化 AggregateException 類別的新執行個體。Initializes a new instance of the AggregateException class with serialized data.

GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

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

對這個 Exception 包含的每個 AggregateException 叫用處理常式。Invokes a handler on each Exception contained by this AggregateException.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

建立並傳回目前 AggregateException 的字串表示。Creates and returns a string representation of the current AggregateException.

事件

SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(繼承來源 Exception)

適用於

執行緒安全性

所有的AggregateException公用和受保護成員都是安全線程, 而且可以從多個執行緒同時使用。All public and protected members of AggregateException are thread-safe and may be used concurrently from multiple threads.